效果图
话不多说,咱们直接看代码
首先第一种:
1、创建自定义View类
public class MyRelative extends View {
public MyRelative(Context context) {
this(context, null); //手动改成this...
}
public MyRelative(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);//手动改成this...
}
@SuppressLint("ResourceAsColor")
public MyRelative(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
2、自定义属性,(在values文件夹下创建一个XML,取名为atts_circle_view.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyRelative"> //这个name最好和你创建的自定义View类名一样
<!--外圆颜色-->
<attr name="outer_color" format="color" />
<!--内圆颜色-->
<attr name="inner_color" format="color" />
<!--圆形宽度-->
<attr name="border_width" format="dimension" />
<!--字体颜色-->
<attr name="step_text_color" format="color" />
<!--字体大小-->
<attr name="step_text_size" format="dimension" />
<!--步数最大值-->
<attr name="max_step" format="integer"/>
<!--当前步数-->
<attr name="curren_step" format="integer"/>
</declare-styleable>
</resources>
3、在第三个构造方法中得到自定义属性
@SuppressLint("ResourceAsColor")
public MyRelative(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRelative);
//圆弧宽度
mBorderWidth = (int) typedArray.getDimension(R.styleable.MyRelative_border_width, 10);
//外圆弧颜色
mOuterColor = typedArray.getColor(R.styleable.MyRelative_outer_color, mOuterColor);
//内圆弧颜色
mInnerColor = typedArray.getInteger(R.styleable.MyRelative_inner_color, mInnerColor);
//字体颜色
mTextColor = typedArray.getColor(R.styleable.MyRelative_step_text_color, mTextColor);
//字体大小
mTextSize = (int) typedArray.getDimensionPixelSize(R.styleable.MyRelative_step_text_size, mTextSize);
//最大步数
mMaxStep = typedArray.getInteger(R.styleable.MyRelative_max_step, 10000);
//当前步数
mCurrentStep = typedArray.getInteger(R.styleable.MyRelative_curren_step, 8000);
typedArray.recycle();
}
4、重写onMeasure方法(测量view大小)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//测量宽高
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
//将控件截成正方形
//三目运算符取长度短的一边作为宽高
setMeasuredDimension(width > height ? height : width, width > height ? height : width);
}
5、重写onDraw方法(绘制)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制内圆弧
int center = getWidth() / 2;
int r = (getWidth() - mBorderWidth) / 2;
RectF rectF = new RectF(mBorderWidth / 2, mBorderWidth / 2, center + r, center + r);
canvas.drawArc(rectF, 135, 270, false, mInnerPaint);
//绘制外圆弧
if (mMaxStep == 0) {
return;
}
float radio = (float) mCurrentStep / mMaxStep;
canvas.drawArc(rectF, 135, 270 * radio, false, mOuterPaint);
//文字
String mText =