Android游戏编程之GameView1

public class MyView extends View{
	private int textX = 20,textY = 20;
	public MyView(Context context) {
		super(context);
		setFocusable(true);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
			textY-= 2;
		}else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
			textY+= 2;
		}else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			textX-= 2;
		}else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			textX+= 2;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		//invalidate();不能在当前子线程中循环调用执行
        //postInvalidate(); 可以在子线程中循环调用执行
		invalidate();
		return super.onKeyUp(keyCode, event);
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();
		textX =x;
		textY = y;
		invalidate();
		return true;
	}
	@Override
	protected void onDraw(Canvas canvas) {
		Paint paint = new Paint();
		paint.setColor(Color.BLUE);
		paint.setTextSize(18);
		canvas.drawText("我厉害不", textX, textY, paint);
		super.onDraw(canvas);
	}
}

Android游戏编程之GameView1_第1张图片

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new MyView(this));
	}
}


你可能感兴趣的:(android游戏)