Android自定義控件——HorizontalRoundProgressBar

在Android開發(fā)中需要橫向圓角進(jìn)度條時可以通過設(shè)置ProgressBar的style和progressDrawable實(shí)現(xiàn)。

原生實(shí)現(xiàn)

  1. 設(shè)置樣式style="@android:style/Widget.ProgressBar.Horizontal"
  2. 設(shè)置進(jìn)度資源android:progressDrawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="8dp" />
            <solid android:color="@android:color/darker_gray" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <scale android:scaleWidth="100%">
            <shape>
                <corners android:radius="8dp" />
                <solid android:color="@android:color/holo_orange_light" />
            </shape>
        </scale>
    </item>

</layer-list>

但是當(dāng)progress值小于圓角半徑甚至更小(progress=1)時進(jìn)度會變成高度撐滿的一條豎線,顯示效果和實(shí)際我們期望的效果有點(diǎn)出入。

繼承已有控件

自定義控件實(shí)現(xiàn)橫向圓角進(jìn)度條

  1. 創(chuàng)建自己的ProgressBar繼承自View
public class HorizontalRoundProgressBar extends View {
}
  1. 在onMeasure方法中計(jì)算寬、高、圓角半徑
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewWidth = getMeasuredWidth();
        mViewHeight = getMeasuredHeight();
        mRadius = mViewHeight / 2f;
    }

  1. 在onDraw方法中自行繪制進(jìn)度條背景、前景
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int progressWidth = (int) (mViewWidth * (mProgress * 1.0f / mMaxProgress) + 0.5f);
        //背景
        onDrawPaint.setColor(mColorBg);
        canvas.drawRoundRect(0, 0, mViewWidth, mViewHeight, mRadius, mRadius, onDrawPaint);
        //前景
        canvas.save();
        onDrawPath.addRoundRect(0, 0, mViewWidth, mViewHeight, mRadius, mRadius, Path.Direction.CW);
        canvas.clipPath(onDrawPath);
        onDrawPaint.setColor(mColorProgress);
        canvas.drawRoundRect(progressWidth - mViewWidth, 0, progressWidth, mViewHeight, mRadius, mRadius, onDrawPaint);
        canvas.restore();
    }

效果圖

HorizontalRoundProgressBar.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容