自定义控件实现大圆、小圆,点击

来源:互联网 发布:江苏扬州高邮网络诈骗 编辑:程序博客网 时间:2024/04/29 05:32

实现如图效果

点击小圆,吐司在小圆内,点击大圆,显示在大圆内,点击圆外显示在圆外,文字必须在圆中心位置

import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Rect;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.widget.Toast;/** * Created by Administrator on 2017/5/1. */public class DrawYuan extends View{//内圆点击的接口回调    interface InClick{        void onInClick();    }    private InClick setonclic;    public void setOnInClickListener(InClick setonclic){        this.setonclic=setonclic;    }//外圆点击的接口回调    interface OutClick{        void onOutClick();    }    private OutClick setoutclic;    public void setOnOutClickListener(OutClick setoutclic){        this.setoutclic=setoutclic;    }    public DrawYuan(Context context) {        super(context);    }    public DrawYuan(Context context, AttributeSet attrs) {        super(context, attrs);    }    public DrawYuan(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        Paint paint=new Paint();        //设置画笔颜色        paint.setColor(Color.GREEN);        canvas.drawColor(Color.GREEN);        //BLUE        paint.setColor(Color.BLUE);        canvas.drawCircle(getWidth()/2,getHeight()/2,getHeight()/2,paint);        //WHITE        paint.setColor(Color.WHITE);        canvas.drawCircle(getWidth()/2,getHeight()/2,getHeight()/4,paint);        //  写文本        String text = "圆环";        paint.setColor(Color.BLACK);        paint.setTextSize(56);        Rect rect = new Rect();        paint.getTextBounds(text, 0, text.length(), rect);        canvas.drawText(text,                0 - rect.left + (getWidth() - rect.width())/2,                0 - rect.top + (getHeight()- rect.height())/2,                paint);//居中显示文本    }    @Override    public boolean onTouchEvent(MotionEvent event) {        float x = event.getX();        float y = event.getY();        //计算触摸点与圆心之间的距离        float sqrt = (float) Math.sqrt((x - getWidth()/2) * (x - getWidth()/2) + (y - getHeight()/2) * (y - getHeight()/2));     //如果触摸事件为"up"        if(event.getAction()==1){            if(sqrt>getHeight()/4&&sqrt<getHeight()/2){                Toast.makeText(getContext(), "外院", Toast.LENGTH_SHORT).show();                setoutclic.onOutClick();            }else if (sqrt<getHeight()/4){                Toast.makeText(getContext(), "内院", Toast.LENGTH_SHORT).show();                setonclic.onInClick();            }else {                Toast.makeText(getContext(), "园外", Toast.LENGTH_SHORT).show();            }        }        return true;    }}
0 0