簡單實現自定義View隨手指拖動
阿新 • • 發佈:2019-02-12
1:自定義一個類繼承View;
private float x=100; private float y=100; private Paint paint;
2:重寫三到四個構造方法
3:在構造方法中初始化筆
public CircleView(Context context, AttributeSet attrs) { super(context, attrs); //初始化畫筆 paint = new Paint(); //設定顏色 paint.setColor(Color.YELLOW); //抗鋸齒 paint.setAntiAlias(true); }4:重寫onDraw方法
protected void5:重寫onTouchEvent方法onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(x,y,100,paint); }
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE:
//在拖動圖形時獲得x值,y值;
x = event.getX(); y = event.getY(); //重新整理invalidate(); //子執行緒重新整理// postInvalidate();break; case MotionEvent.ACTION_UP: break; } return true; }
6:在activity的佈局xml檔案中引用就可以了