public class Yuan extends View {
private int mCurrent;//当前进度
private Paint mPaintOut;
private Paint mPaintCurrent;
private Paint mPaintText;
private RectF rectF;
private int width;
private int height;
private OnLoadingCompleteListener mLoadingCompleteListener;
private int mWidth;
public Yuan(Context context) {
this(context, null);
}
public Yuan(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public Yuan(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//画笔->背景圆弧
mPaintOut = new Paint();
mPaintOut.setAntiAlias(true);
mPaintOut.setStrokeWidth(16f);
mPaintOut.setStyle(Paint.Style.STROKE);
mPaintOut.setColor(Color.GRAY);
mPaintOut.setStrokeCap(Paint.Cap.ROUND);
//画笔->进度圆弧
mPaintCurrent = new Paint();
mPaintCurrent.setAntiAlias(true);
mPaintCurrent.setStrokeWidth(16f);
mPaintCurrent.setStyle(Paint.Style.STROKE);
mPaintCurrent.setColor(Color.RED);
mPaintCurrent.setStrokeCap(Paint.Cap.ROUND);
//画笔->绘制字体
mPaintText = new Paint();
mPaintText.setAntiAlias(true);
mPaintText.setStyle(Paint.Style.FILL);
mPaintText.setColor(Color.BLACK);
mPaintText.setStrokeWidth(10f);
mPaintText.setTextSize(18f);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
width = getMeasuredWidth();
height = getMeasuredHeight();
rectF = new RectF(0, 0, width, height);
setMeasuredDimension(300, 300);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawArc(rectF, 0, 360, false, mPaintOut);
//绘制当前进度
float sweepAngle = 360 * mCurrent / 100;
canvas.drawArc(rectF, 360, sweepAngle, false, mPaintCurrent);
//绘制进度数字
String text = mCurrent + "%";
//获取文字宽度
float textWidth = mPaintText.measureText(text, 0, text.length());
float dx = getWidth() / 2 - textWidth / 2;
Paint.FontMetricsInt fontMetricsInt = mPaintText.getFontMetricsInt();
float dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
float baseLine = getHeight() / 2 + dy;
canvas.drawText(text, dx, baseLine, mPaintText);
if (mLoadingCompleteListener != null && mCurrent == 100) {
mLoadingCompleteListener.complete();
}
}
/**
* 设置当前进度并重新绘制界面
*
* @param mCurrent
*/
public void setmCurrent(int mCurrent) {
this.mCurrent = mCurrent;
invalidate();
}
public void setOnLoadingCompleteListener(OnLoadingCompleteListener loadingCompleteListener) {
this.mLoadingCompleteListener = loadingCompleteListener;
}
public interface OnLoadingCompleteListener {
void complete();
}
}