import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class Yuan extends View{
int x=0;
int y=0;
Paint mPaint;
Boolean weizhi;
public Yuan(Context context) {
super(context);
}
public Yuan(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mPaint=new Paint();
mPaint.setColor(Color.RED);
mPaint.setAlpha(200);
mPaint.setStrokeWidth(8);
mPaint.setAntiAlias(true);
}
public Yuan(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
x = this.getWidth()/2;
y = this.getHeight()/2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x,y,50,mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
mPaint.setColor(Color.BLUE);
int dx = (int) event.getX();
int dy = (int) event.getY();
weizhi = weizhi(dx, dy);
break;
case MotionEvent.ACTION_MOVE:
int mx = (int) event.getX();
int my = (int) event.getY();
if (weizhi){
x=mx;
y=my;
invalidate();
}
break;
case MotionEvent.ACTION_UP:
mPaint.setColor(Color.BLUE);
break;
}
return true;
}
private Boolean weizhi(int dx, int dy) {
double sqrt = Math.sqrt((dx - x) * (dx - x) + (dy - y) * (dy - y));
if (sqrt<=50){
return true;
}
return false;
}
}
<liyuanqi.bwie.com.zidingyikj01.Yuan
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />