public class MyTextView extends View {
private String content;
private int color;
private float size;
private Paint mPaint;
public MyTextView(Context context) {
this(context, null);
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//在这里获取在布局文件里面的属性,然后将属性绘制到控件里面
// attrs 就是在xml布局文件里面设置的属性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyleAttr, 0);//获取样式属性的
//取出属性
//获取字符串
content = ta.getString(R.styleable.MyTextView_content);
color = ta.getColor(R.styleable.MyTextView_myColor, Color.BLUE);
size = ta.getDimension(R.styleable.MyTextView_mySize, 40);
android.util.Log.d(TAG, "MyTextView() returned: " + content + "--" + color + "--" + size);
//初始化画笔
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(color);
mPaint.setTextSize(size);
}
//绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制文本
//参数1.要绘制的内容
//参数2.开始的x轴坐标
//参数3.开始的y轴坐标
//画笔
//矩形
Rect rect = new Rect();
mPaint.getTextBounds(content,0,content.length(),rect);
canvas.drawText(content, 0, rect.height(), mPaint);
}
//测量的方法
//测量宽高的
//测量模式 和 测量尺寸
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取测量模式和测量的尺寸
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
//如果测量模式是EXACTLY 就直接显示测量尺寸就行
int width;
int height;
if (widthMode==MeasureSpec.EXACTLY){
width = widthSize;
}else {
//控件的宽度需要测量,
//控件的宽度 = 文字的宽度+左边距+右边距
Rect bound = new Rect();
mPaint.getTextBounds(content,0,content.length(),bound);//将文字用矩形括起来,那么矩形的尺寸就是文字的尺寸
int width1 = bound.width();
width = width1+getPaddingLeft()+getPaddingRight();
}
//处理高度
if (heightMode==MeasureSpec.EXACTLY){
height = heightSize;
}else {
//控件的高度 = 文字的高度+上边距+下边距
Rect bound = new Rect();
mPaint.getTextBounds(content,0,content.length(),bound);//将文字用矩形括起来,那么矩形的尺寸就是文字的尺寸
int height1 = bound.height();
height = height1+getPaddingTop()+getPaddingBottom();
}
//将宽高重新赋值
setMeasuredDimension(width,height);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
}
// values里
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="mytext" format="string"></attr> <attr name="mycolor" format="color"></attr> <attr name="mysizi" format="dimension"></attr> <declare-styleable name="attrss"> <attr name="mytext"></attr> <attr name="mycolor"></attr> <attr name="mysizi"></attr> </declare-styleable> </resources>