自定义View画圆,实现鼠标拖动画的圆跟着动
先看效果
自定义控件主要的就是自己定义一个类来实现自己想要的,布局和MainActivity里面都没动,所以就不粘里面的代码了
先定义一个类,
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by BAIPEI on 2017/11/30. */ public class BallView extends View { Paint paint; int cx=200; int cy=300; public BallView(Context context) { super(context); initData(); } private void initData() { paint=new Paint(); //设置画笔颜色 paint.setColor(Color.RED); //设置画笔的宽度 paint.setStrokeWidth(20); //设置一个实心的 paint.setStyle(Paint.Style.FILL); //抗锯齿 paint.setAntiAlias(true); } public BallView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initData(); } public BallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initData(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){
//当手指按下会触发ACTION_DOWN case MotionEvent.ACTION_DOWN: cx = (int) event.getX(); cy = (int) event.getY(); //invalidate刷新 //invalidate(); //postInvalidate重新画 postInvalidate();//该方法会调用onDraw方法,重新绘图 break;
//当手指滑动会触发ACTION_MOVE case MotionEvent.ACTION_MOVE: // 移动 cx = (int) event.getX(); cy = (int) event.getY(); //invalidate刷新 //invalidate(); //postInvalidate重新画
//该方法会调用onDraw方法,重新绘图 postInvalidate(); break;
//当手指抬起会触发ACTION_UP
case MotionEvent.ACTION_UP:
cx = (int) event.getX();
cy = (int) event.getY();
//invalidate刷新
//invalidate();
//postInvalidate重新画
//该方法会调用onDraw方法,重新绘图
postInvalidate();
break;
}
/*
* 备注1:此处一定要将return super.onTouchEvent(event)修改为return true,原因是:
* 1)父类的onTouchEvent(event)方法可能没有做任何处理,但是返回了false。
* 2)一旦返回false,在该方法中再也不会收到MotionEvent.ACTION_MOVE及MotionEvent.ACTION_UP事件。
*/
//return super.onTouchEvent(event);
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画圆
canvas.drawCircle(cx,cy,100,paint);
}
}