android自定义TextView实现绘制圆圈

来源:互联网 发布:youtube软件google服务 编辑:程序博客网 时间:2024/05/31 00:40

很多时候在开发中我们经常会使用到各种各样的效果。今天我们就来学习一下在android中使用自定义的TextView来实现绘制圆圈的效果。废话不多说,我们先看效果再看代码。
这里写图片描述

public class CircleTextView extends TextView {    private Paint mPaint;    public CircleTextView(Context context) {        super(context);    }    public CircleTextView(Context context, AttributeSet attrs) {        super(context, attrs);    }    public CircleTextView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        mPaint = new Paint();        //创建一个RectF,用来限定绘制圆弧的范围        RectF rectf = new RectF();        //设置画笔的颜色        mPaint.setColor(Color.GRAY);        //设置画笔的样式        mPaint.setStyle(Paint.Style.STROKE);        //设置抗锯齿        mPaint.setAntiAlias(true);        //设置画得一个半径,然后比较长和宽,以最大的值来确定长方形的长宽,确定半径        int r = getMeasuredWidth() > getMeasuredHeight() ? getMeasuredWidth() : getMeasuredHeight();        rectf.set(getPaddingLeft(), getPaddingTop(), r - getPaddingRight(), r - getPaddingBottom());        String testString ="CircleTextView";        Rect bounds = new Rect();        Paint paint=new Paint();        paint.setColor(Color.BLUE);        paint.setStyle(Paint.Style.FILL);        paint.getTextBounds(testString, 0, testString.length(), bounds);        //绘制文字        canvas.drawText(testString, getMeasuredWidth() / 2 - bounds.width() / 2, getMeasuredHeight() / 2 + bounds.height() / 2, paint);        //绘制圆弧        canvas.drawArc(rectf, 0, 360, false, mPaint);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }}
0 0
原创粉丝点击