public class DrawView extends View { public DrawView(Context context) { super(context); } }
//畫筆 private Paint paint; //當前X座標 private float currentX; //當前Y座標 private float currentY; public DrawView(Context context) { super(context); this.paint = new Paint(); this.currentX = 100; this.currentY = 100; }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //設置畫筆顏色 paint.setColor(Color.RED); //繪製圓形,中心位置(currentX, currentY),半徑10 canvas.drawCircle(currentX, currentY, 10, paint); }
@Override public boolean onTouchEvent(MotionEvent event) { //獲取點擊事件的座標x,y currentX = event.getX(); currentY = event.getY(); //重繪控件 invalidate(); return true; }
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout); DrawView draw = new DrawView(this); layout.addView(draw);