Android
[CustomView] 4. Thread 이용하여 그림 움직이기
인뜨라야
2010. 8. 12. 12:46
#Thread 이용하여 그림 움직이기
[RobotView.java]
package net.itisn.test; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class RobotView extends View implements Runnable { private final static int STEP = 10; private Drawable image; private int viewWidth, viewHeight; private int imageWidth, imageHeight; private int x, y; public RobotView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub image = this.getResources().getDrawable(R.drawable.su); Thread thread = new Thread(this); thread.start(); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub image.setBounds(x, y, x + imageWidth, y + imageHeight); image.draw(canvas); super.onDraw(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { // TODO Auto-generated method stub viewWidth = this.getWidth(); viewHeight = this.getHeight(); imageWidth = image.getIntrinsicWidth(); imageHeight = image.getIntrinsicHeight(); x = viewWidth / 2 - imageWidth / 2; y = viewHeight / 2 - imageHeight / 2; super.onSizeChanged(w, h, oldw, oldh); } @Override public void run() { // TODO Auto-generated method stub for (; ;) { try { Thread.sleep(500); y = Math.min(viewHeight - imageHeight, y + STEP); this.postInvalidate(); } catch(InterruptedException e) { e.printStackTrace(); } } } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub x = (int)event.getX(); y = (int)event.getY(); this.invalidate(); return super.onTouchEvent(event); } } |
[main.xml]
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <net.itisn.test.RobotView android:id="@+id/su" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </LinearLayout> |
따라서 try catch 문을 반드시 써주어야 함
static 클래스는 new 연산자 없이 바로 사용가능.
Math.min
System.out.println();
원래 System sys = new System();
sys.out.println()
postInvalidate() 화면을 새로 그림..
ontouchEvent
x = (int)event.getx();
y = (int)event.gety();
this.invalidate();
return true;
- END