***ToothView类***
public class ToothView extends View {
//红色
public static final int COLOR_RED=Color.RED;
//画笔的宽度
public static final int PAINT_WIDTH=5;
//圆的半径
public static final int RADIO=40;
//圆位置的X坐标
public static final int X=100;
//圆位置的Y坐标
public static final int Y=100;
//定义一个对象
ClickCirle circleListener;
public ToothView(Context context) {
super(context);
}
public ToothView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ToothView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//测量高度
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
//绘制图形
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//调用绘制圆的方法
Circle(canvas);
}
//设置布局
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
//绘制圆的方法
public void Circle(Canvas canvas){
//声明一个画笔
Paint paint=new Paint();
//设置画笔的样式、颜色
paint.setColor(COLOR_RED);
//设置空心圆
paint.setStyle(Paint.Style.STROKE);
//设置画笔的宽度
paint.setStrokeWidth(PAINT_WIDTH);
//设置锯齿true表示抗锯齿,false表示不抗锯齿
paint.setAntiAlias(true);
//绘制圆
canvas.drawCircle(X,Y,RADIO,paint);
}
//封装一个监听的方法
public void setCircleListener(ClickCirle circleListener) {
this.circleListener = circleListener;
}
//观察者模式
public interface ClickCirle{
//点击的方法
public void click();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//获取当前的位置
float x=event.getX();
float y=event.getY();
//调用点击事件方法
ClickWhere(x,y);
return super.onTouchEvent(event);
}
//封装判断点击的方法
public void ClickWhere(float x,float y){
int distanx =(int) ((x-X)*(x-X));
int distany =(int) ((y-Y)*(y-Y));
//求和
int sum=distanx+distany;
if(sum<RADIO*RADIO){
//设置观察者
if(null!=circleListener){
circleListener.click();
}
}
}
***主方法***
public class MainActivity extends AppCompatActivity {
ToothView tooth_main;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tooth_main = (ToothView)findViewById(R.id.tooth_main);
tooth_main.setCircleListener(new ToothView.ClickCirle() {
@Override
public void click() {
Toast.makeText(getApplicationContext(), "方法被点击", Toast.LENGTH_LONG).show();
}
});
}
自定义View画圆(观察者模式)
最新推荐文章于 2019-09-20 08:00:00 发布