简单实现自定义View随手指拖动

xiaoxiao2021-02-28  113

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 void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(x,y,100,paint); } 5:重写onTouchEvent方法 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文件中引用就可以了

转载请注明原文地址: https://www.6miu.com/read-21425.html

最新回复(0)