效果图 package com.github.lzyzsd.circleprogressexample; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * @Class: MyCircleView * @Description: * @author: zm * @Date: 2019/7/17 0017 */ public class MyCircleView extends View { //底部圆 Paint bgCirclePaint; //进度圆 Paint progressCirclePaint; //文本 Paint textPaint; //绘制区域 RectF rectF = new RectF(); private int progress ; public MyCircleView(Context context) { this(context,null); } public MyCircleView(Context context, @Nullable AttributeSet attrs) { this(context,attrs,0); } public MyCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { bgCirclePaint = new Paint(); bgCirclePaint.setAntiAlias(true); bgCirclePaint.setColor(Color.BLACK); progressCirclePaint = new Paint(); progressCirclePaint.setAntiAlias(true); progressCirclePaint.setColor(Color.RED); textPaint = new Paint(); textPaint.setTextSize(30f); textPaint.setAntiAlias(true); textPaint.setColor(Color.WHITE); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //测量高度 此处固定了宽高,类型是 MeasureSpec.EXACTLY ,另外两种情况未处理 setMeasuredDimension(widthMeasureSpec,heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); rectF.set(0,0,width,height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //绘制圆 canvas.drawCircle(getWidth()/2f,getHeight()/2f,getWidth()/2,bgCirclePaint); /** * 如图(重点)保持和水平直径平行,根据进度比计算startAngle 、 sweepAngle * * sweepAngle = progress/100f * 360 * * startAngle =90 - sweepAngle/2.0f(两条水平线的夹角相等) * * 以竖直手机屏幕为准,水平直径右端点为绘制圆的起始点,向上为逆时针(- degree),反之(+degree) */ canvas.drawArc(rectF,90-progress/100f*180,progress/100f*360,false,progressCirclePaint); //绘制文本X轴 float width = getWidth()/2.0f - textPaint.measureText(String.valueOf(progress))/2.0f +getPaddingLeft(); //文本基线 float baseLine = getHeight()/2+(Math.abs(textPaint.ascent())-textPaint.descent())/2; //绘制文本 canvas.drawText(String.valueOf(progress)+"%",width,baseLine,textPaint); canvas.save(); } public void setProgress(int progress){ if (progress<0) { progress = 0; } if (progress>100) { progress = 100; } this.progress = progress; invalidate(); } public int getProgress(){ return progress; } }
角1 = 角2
最近在学自定义view,记录一下,希望自己在这方面有所突破