自定义View(一)

来源:互联网 发布:净水壶 净水器 知乎 编辑:程序博客网 时间:2024/05/20 16:34
public class Circle extends View {    Paint mPaint;    Paint mWordPaint;    Paint mPoint;    float width;    float height;    String textContent = "ABC";    public Circle(Context context) {        this(context, null);    }    public Circle(Context context, @Nullable AttributeSet attrs) {        this(context, attrs, 0);    }    public Circle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        mPaint = new Paint();        mWordPaint = new Paint();        mPoint = new Paint();    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        /**         * 获取在加载该View时给的宽高,(以下具体的宽高是200dp,200dp)            <com.b.widget.Circle                android:layout_width="200dp"                android:layout_height="200dp"                android:background="#f00"/>         */        width = getMeasuredWidth();        height = getMeasuredHeight();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        mPaint.setColor(Color.GRAY);        mWordPaint.setColor(Color.RED);        mPoint.setColor(Color.BLACK);        mWordPaint.setTextSize(60);        //半径        float radius = width > height ? height / 2 : width / 2;        //画圆参数含义(圆心横坐标,圆心纵坐标,半径,画笔对象)        canvas.drawCircle(width / 2, height / 2, radius, mPaint);        Rect rect = new Rect();        //getTextBounds 参数的含义(字符串内容,开始计数位置,结束计数位置,返回的rect对象)        //得到的rect就可以获取文字的宽高        mWordPaint.getTextBounds(textContent, 0, textContent.length(), rect);        //画文字,参数含义(文字内容,文字左下端的横坐标,文字左下端的纵坐标,画笔对象)        //在具体的操作过程中要考虑到文字的本身的宽高,才能将文字画在中心位置        canvas.drawText(textContent, width / 2 - rect.width() / 2, height / 2 + rect.height() / 2, mWordPaint);        canvas.drawCircle(width / 2, height / 2, 10, mPoint);    }}
原创粉丝点击