public class Custom extends View{
Paint paint;
private float cx; //圆点默认X坐标
private float cy; //圆点默认Y坐标
private int radius = 40;
private int mX1;
private int mY1;
private boolean mHasBall;
int width;
int height;
Rect rect = new Rect();
public Custom(Context context) {
this(context,null);
}
public Custom(Context context, @Nullable AttributeSet attrs) {
this(context,attrs,0);
}
public Custom(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initData();
}
private void initData() {
paint = new Paint();
//设置消除锯齿
paint.setAntiAlias(true);
//设置画笔颜色
paint.setColor(Color.RED);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = this.getWidth();
height = this.getHeight();
cx= width/2;
cy=height/2;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//将屏幕设置为白色
canvas.drawColor(Color.WHITE);
//修正圆点坐标
revise();
//随机设置画笔颜色
//setPaintRandomColor();
//绘制小圆作为小球
canvas.drawCircle(cx, cy, radius, paint);
}
//修正圆点坐标
private void revise() {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // 按下
mX1 = (int) event.getX();
mY1 = (int) event.getY();// 通知重绘
mHasBall = isHasBall(mX1, mY1);
break;
case MotionEvent.ACTION_MOVE: // 移动
if (mHasBall) {
this.cx = event.getX();
this.cy = event.getY();
postInvalidate();
}
break;
case MotionEvent.ACTION_UP: // 抬起
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;
}
private boolean isHasBall(int x1, int y1) {
double sqrt = Math.sqrt((x1 - cx) * (x1 - cx) + (y1 - cy) * (y1 - cy));
if (sqrt < radius) {
return true;
}
return false;
}
}
拖动小圆球
猜你喜欢
转载自blog.csdn.net/FanRQ_/article/details/83743098
今日推荐
周排行