public class Myview extends View { //圆的半径 private int cp=50; //圆心的x轴坐标 private float currentx=cp; //圆心的y轴坐标 private float currenty=cp; //画笔 private Paint paint; //控制是否可移动,ture的时候为移动 private boolean move; public Myview(Context context) { super(context); } public Myview(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public Myview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //画笔 paint = new Paint(); //画笔的颜色 paint.setColor(Color.BLACK); //根据圆心的坐标来绘制圆的位置的,而圆心的坐标,我们触摸屏幕的时候被我们修改了 canvas.drawCircle(currentx,currenty,cp,paint); } @Override public boolean onTouchEvent(MotionEvent event) { //定义触摸时的坐标 float touchx; float touchy; switch (event.getAction()){ //判断在圆上的时候再滑动 case MotionEvent.ACTION_DOWN: touchx=event.getX(); touchy=event.getY(); if (touchx>currentx-cp&&touchx<currentx+cp&&touchy>currenty-cp&&touchy<currenty+cp){ move=true; }else { move=false; } case MotionEvent.ACTION_MOVE: if (move){ currentx=event.getX(); currenty=event.getY(); //重新绘制圆 invalidate(); } break; case MotionEvent.ACTION_UP: break; } return true; } } //xml布局文件 //在需要的布局里调用 调用的方法为包名+类名 就是上面的代码<com.bawei.wk.myapplication.Myview android:layout_width="match_parent" android:layout_height="match_parent" />
自定义view画圆 单点拖动
最新推荐文章于 2022-09-14 15:42:29 发布