您的位置:首页 > 移动开发 > Android开发

android自定义TextView实现绘制圆圈

2016-11-11 15:43 453 查看
很多时候在开发中我们经常会使用到各种各样的效果。今天我们就来学习一下在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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android textview class