使用自定义View绘制圆形进度条效果

在这里插入图片描述
首先自定义属性 res - values - attrs(自己创建):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCicle">

        <!--画笔的宽度-->
        <attr name="progress_paint_width" format="dimension" />
        <!--画笔颜色-->
        <attr name="progress_paint_color" format="color" />
        <!--字体颜色-->
        <attr name="progress_text_color" format="color" />
        <!--字体尺寸-->
        <attr name="progress_text_size" format="dimension" />
        <!--加载进度的开始位置-->
        <attr name="location" format="enum">
            <enum name="left" value="1" />
            <enum name="top" value="2" />
            <enum name="right" value="3" />
            <enum name="bottom" value="4" />
        </attr>

    </declare-styleable>
</resources>

自定义布局类:

/**
 * date:2018/11/22
 * author:(家辉辉辉)
 * function:圆形进度条
 * 思路:
 *      1.自定义属性:文字的颜色和字体大小,圆弧的颜色和宽度,一开始加载进度的位置;
 *      2.画出需要的效果:画圆弧,画字体,使用画笔paint在canvas上绘制;
 *      3.设置进度,重新绘制;
 *      4.接口回调。
 *   
 */
public class MyCicle extends View {

    private int mCurrent;//当前进度
    private Paint mPaintOut;
    private Paint mPaintCurrent;
    private Paint mPaintText;
    private float mPaintWidth;//画笔宽度
    private int mPaintColor = Color.RED;//画笔颜色
    private int mTextColor = Color.BLACK;//字体颜色
    private float mTextSize;//字体大小
    private int location;//从哪个位置开始
    private float startAngle;//开始角度



    public MyCicle(Context context) {
        this(context,null);
    }

    public MyCicle(Context context,AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyCicle(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化attrs.xml
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyCicle);
        location = array.getInt(R.styleable.MyCicle_location, 1);
        mPaintWidth = array.getDimension(R.styleable.MyCicle_progress_paint_width, dip2px(context, 4));//默认4dp
        mPaintColor = array.getColor(R.styleable.MyCicle_progress_paint_color, mPaintColor);
        mTextSize = array.getDimension(R.styleable.MyCicle_progress_text_size, dip2px(context, 18));//默认18sp
        mTextColor = array.getColor(R.styleable.MyCicle_progress_text_color, mTextColor);
        array.recycle();

        //画笔->背景圆弧
        mPaintOut = new Paint();
        mPaintOut.setAntiAlias(true);
        mPaintOut.setStrokeWidth(mPaintWidth);
        mPaintOut.setStyle(Paint.Style.STROKE);
        mPaintOut.setColor(Color.GRAY);
        mPaintOut.setStrokeCap(Paint.Cap.ROUND);

        //画笔->进度圆弧
        mPaintCurrent = new Paint();
        mPaintCurrent.setAntiAlias(true);
        mPaintCurrent.setStrokeWidth(mPaintWidth);
        mPaintCurrent.setStyle(Paint.Style.STROKE);
        mPaintCurrent.setColor(mPaintColor);
        mPaintCurrent.setStrokeCap(Paint.Cap.ROUND);

        //画笔->绘制字体
        mPaintText = new Paint();
        mPaintText.setAntiAlias(true);
        mPaintText.setStyle(Paint.Style.FILL);
        mPaintText.setColor(mTextColor);
        mPaintText.setTextSize(mTextSize);

        if (location == 1) {//默认从左侧开始
            startAngle = -180;
        } else if (location == 2) {
            startAngle = -90;
        } else if (location == 3) {
            startAngle = 0;
        } else if (location == 4) {
            startAngle = 90;
        }

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     * */
    private float dip2px(Context context, int dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int size = width > height ? height : width;
        setMeasuredDimension(size, size);
    }

    @Override//绘制
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //绘制背景圆弧,因为画笔有一定的宽度,所有画圆弧的范围要比View本身的大小稍微小一些,不然画笔画出来的东西会显示不完整
        RectF rectF = new RectF(mPaintWidth / 2, mPaintWidth / 2, getWidth() - mPaintWidth / 2, getHeight() - mPaintWidth / 2);
        canvas.drawArc(rectF, 0, 360, false, mPaintOut);

        //绘制当前进度
        float sweepAngle = 360 * mCurrent / 100;
        canvas.drawArc(rectF, startAngle, 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();
        }




    }

    /**
     * 获取当前进度值
     *
     * @return
     */
    public int getmCurrent() {
        return mCurrent;
    }

    /**
     * 设置当前进度并重新绘制界面
     *
     * @param mCurrent
     */
    public void setmCurrent(int mCurrent) {
        this.mCurrent = mCurrent;
        invalidate();
    }

    //创建接口
    public interface OnLoadingCompleteListener {
        void complete();
    }

    //声明接口
    private OnLoadingCompleteListener mLoadingCompleteListener;

    //设置暴露方法
    public void setOnLoadingCompleteListener(OnLoadingCompleteListener loadingCompleteListener) {
        this.mLoadingCompleteListener = loadingCompleteListener;
    }

}

MainActicity布局

<com.wjh.activity.myview.MyCicle
        android:id="@+id/mycicle"
        android:layout_width="150dp"
        android:layout_height="150dp"
        app:location="left"
        app:progress_paint_color="#10c4f1"
        app:progress_paint_width="4dp"
        app:progress_text_color="#3F51B5"
        app:progress_text_size="20sp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="55dp"/>

MainActivity代码:

public class MainActivity extends AppCompatActivity {

    private MyCicle mMyCicle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //找控件
        mMyCicle = findViewById(R.id.mycicle);

        //进度条从0到100
        ValueAnimator animator = ValueAnimator.ofFloat(0, 100);
        animator.setDuration(4000);
        animator.setInterpolator(new LinearInterpolator());

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float current = (float) animation.getAnimatedValue();
                mMyCicle.setmCurrent((int) current);
            }
        });

        animator.start();

       //使用接口回调
        mMyCicle.setOnLoadingCompleteListener(new MyCicle.OnLoadingCompleteListener() {
            @Override
            public void complete() {
                Toast.makeText(MainActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

详解查看: https://www.jianshu.com/p/be71f6ffe512

猜你喜欢

转载自blog.csdn.net/jiahui6666/article/details/84334521