본문 바로가기

정보기술, IT/IT source

Android 터치(Touch) 한 곳에 객체 생성하기. 이미지그리기.

 

1) ------------------------------MyShape 클래스  

 

public class MyShape {
 
 private int cx;
 private int cy;
 public static final int SHAPE_SIZE = 72;
 Random rnd = new Random();
 
 public MyShape(){
  cx=rnd.nextInt(MyView.VIEW_W)+40;
  cy=rnd.nextInt(MyView.VIEW_H)+50;
 } 
 
 public MyShape(int x, int y){
  cx = x;
  cy = y;
 }
 
 public void display(Canvas c, Bitmap bitmap){

  c.drawBitmap(bitmap, cx-(SHAPE_SIZE/2), cy-(SHAPE_SIZE/2), null);
  
 }
 
}; 

 

 

2) --------------------------------MyView 클래스

 

public class MyView extends View {

 public static final int VIEW_W = 360;
 public static final int VIEW_H = 700;

 ArrayList<MyShape> arr = new ArrayList<MyShape>();
 Bitmap bitmap;

 public MyView(Context context) {
  super(context);
  bitmap = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

 }

 @Override
 protected void onDraw(Canvas c) {// 콜백. 시스템에서 부른다.

  for (int i = 0; i < arr.size(); i++) {
   arr.get(i).display(c, bitmap); //ArrayList안에 있는 객체를 가져오기 위해 get이라는 명령어를 수행한후 get(MyShape안에 있는)의 display를 그려준다.
  }

 }

 

 @Override
 public boolean onTouchEvent(MotionEvent event) {// 콜백. 시스템에서 부른다.
  super.onTouchEvent(event);

  if (event.getAction() == MotionEvent.ACTION_DOWN) {

   MyShape temp = new MyShape((int) event.getX(), (int) event.getY());
   arr.add(temp); //ArrayList 문법이다. 객체를 배열에 붙이기 위해 add를 사용한다.
  }

  invalidate(); //Repaint와 같은 명령어이다.
  return true;
 }

};