Android自定義圓弧進(jìn)度條

挺久沒寫文章了,近段時間被拉過去寫JS項目了,在做一個項目的時候,遇到一個新的需求就是空氣質(zhì)量,實現(xiàn)空氣污染指數(shù)的時候,需要到一個圓弧的進(jìn)度,在網(wǎng)上沒找到合適,干脆就自己寫了一個,順便復(fù)習(xí)一下自定義View,下面是具體的實現(xiàn)。

先看一下效果

這里的話我只做一個進(jìn)度條,使用也很簡單。圓弧外的文本是一個textview,不是這個控件里面的,說明一下。

下面先看一下整體的代碼:

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class ArcProgressBar extends View {

private static final String TAG = "ArcProgressBar";
/**
 * 圓弧的寬度
 */
private int mStrokeWidth = dp2px(8);
/**
 * 圓弧開始的角度
 */
private float mStartAngle = 135;
/**
 * 起點角度和終點角度對應(yīng)的夾角大小
 */
private float mAngleSize = 270;
/**
 * 圓弧背景顏色
 */
private int mArcBgColor = Color.YELLOW;
/**
 * 最大的進(jìn)度,用于計算進(jìn)度與夾角的比例
 */
private float mMaxProgress = 500;
/**
 * 當(dāng)前進(jìn)度對應(yīng)的起點角度到當(dāng)前進(jìn)度角度夾角的大小
 */
private float mCurrentAngleSize = 0;
/**
 * 當(dāng)前進(jìn)度
 */
private float mCurrentProgress = 0;
/**
 * 動畫的執(zhí)行時長
 */
private long mDuration = 3000;
/**
 * 進(jìn)度圓弧的顏色
 */
private int mProgressColor = Color.RED;
/**
 * 第一行文本
 */
private String mFirstText = "42";
/**
 * 第一行文本的顏色
 */
private int mFirstTextColor = Color.RED;
/**
 * 第一行文本的字體大小
 */
private float mFirstTextSize = 56f;
/**
 * 第二行文本
 */
private String mSecondText = "優(yōu)";
/**
 * 第二行文本的顏色
 */
private int mSecondTextColor = Color.RED;
/**
 * 第二行文本的字體大小
 */
private float mSecondTextSize = 56f;


public ArcProgressBar(Context context) {
    super(context, null);
}

public ArcProgressBar(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs, 0);

}

public ArcProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initAttr(context, attrs);
}

/**
 * 設(shè)置初始化的參數(shù)
 *
 * @param context
 * @param attrs
 */
private void initAttr(Context context, AttributeSet attrs) {
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ArcProgressBar);
    mMaxProgress = array.getFloat(R.styleable.ArcProgressBar_arc_max_progress, 500f);
    mArcBgColor = array.getColor(R.styleable.ArcProgressBar_arc_bg_color, Color.YELLOW);
    mStrokeWidth = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_stroke_width, 12f));
    mCurrentProgress = array.getFloat(R.styleable.ArcProgressBar_arc_progress, 300f);
    mProgressColor = array.getColor(R.styleable.ArcProgressBar_arc_progress_color, Color.RED);
    mFirstText = array.getString(R.styleable.ArcProgressBar_arc_first_text);
    mFirstTextSize = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_first_text_size, 20f));
    mFirstTextColor = array.getColor(R.styleable.ArcProgressBar_arc_first_text_color, Color.RED);
    mSecondText = array.getString(R.styleable.ArcProgressBar_arc_second_text);
    mSecondTextSize = dp2px(array.getDimension(R.styleable.ArcProgressBar_arc_second_text_size, 20f));
    mSecondTextColor = array.getColor(R.styleable.ArcProgressBar_arc_second_text_color, Color.RED);
    mAngleSize = array.getFloat(R.styleable.ArcProgressBar_arc_angle_size, 270f);
    mStartAngle = array.getFloat(R.styleable.ArcProgressBar_arc_start_angle, 135f);
    array.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int centerX = getWidth() / 2;
    RectF rectF = new RectF();
    rectF.left = mStrokeWidth;
    rectF.top = mStrokeWidth;
    rectF.right = centerX * 2 - mStrokeWidth;
    rectF.bottom = centerX * 2 - mStrokeWidth;
    //畫最外層的圓弧
    drawArcBg(canvas, rectF);
    //畫進(jìn)度
    drawArcProgress(canvas, rectF);
    //繪制第一級文本
    drawFirstText(canvas, centerX);
    //繪制第二級文本
    drawSecondText(canvas, centerX);

}


/**
 * 畫最開始的圓弧
 *
 * @param canvas
 * @param rectF
 */
private void drawArcBg(Canvas canvas, RectF rectF) {
    Paint mPaint = new Paint();
    //畫筆的填充樣式,Paint.Style.FILL 填充內(nèi)部;Paint.Style.FILL_AND_STROKE 填充內(nèi)部和描邊;Paint.Style.STROKE 描邊
    mPaint.setStyle(Paint.Style.STROKE);
    //圓弧的寬度
    mPaint.setStrokeWidth(mStrokeWidth);
    //抗鋸齒
    mPaint.setAntiAlias(true);
    //畫筆的顏色
    mPaint.setColor(mArcBgColor);
    //畫筆的樣式 Paint.Cap.Round 圓形,Cap.SQUARE 方形
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    //開始畫圓弧
    canvas.drawArc(rectF, mStartAngle, mAngleSize, false, mPaint);
}

/**
 * 畫進(jìn)度的圓弧
 *
 * @param canvas
 * @param rectF
 */
private void drawArcProgress(Canvas canvas, RectF rectF) {
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(mStrokeWidth);
    paint.setColor(mProgressColor);
    paint.setAntiAlias(true);
    paint.setStrokeCap(Paint.Cap.ROUND);
    canvas.drawArc(rectF, mStartAngle, mCurrentAngleSize, false, paint);
}


/**
 * 繪制第一級文字
 *
 * @param canvas  畫筆
 * @param centerX 位置
 */
private void drawFirstText(Canvas canvas, float centerX) {
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(mFirstTextColor);
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(mFirstTextSize);
    Rect firstTextBounds = new Rect();
    paint.getTextBounds(mFirstText, 0, mFirstText.length(), firstTextBounds);
    canvas.drawText(mFirstText, centerX, firstTextBounds.height() / 2 + getHeight() * 2 / 5, paint);
}

/**
 * 繪制第二級文本
 *
 * @param canvas  畫筆
 * @param centerX 文本
 */
private void drawSecondText(Canvas canvas, float centerX) {
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(mSecondTextColor);
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(mSecondTextSize);
    Rect bounds = new Rect();
    paint.getTextBounds(mSecondText, 0, mSecondText.length(), bounds);
    canvas.drawText(mSecondText, centerX, getHeight() / 2 + bounds.height() / 2 +
            getFontHeight(mSecondText, mSecondTextSize), paint);
}

/**
 * 設(shè)置最大的進(jìn)度
 *
 * @param progress
 */
public void setMaxProgress(int progress) {
    if (progress < 0) {
        throw new IllegalArgumentException("Progress value can not be less than 0 ");
    }
    mMaxProgress = progress;
}

/**
 * 設(shè)置當(dāng)前進(jìn)度
 *
 * @param progress
 */
public void setProgress(float progress) {
    if (progress < 0) {
        throw new IllegalArgumentException("Progress value can not be less than 0");
    }
    if (progress > mMaxProgress) {
        progress = mMaxProgress;
    }
    mCurrentProgress = progress;
    float size = mCurrentProgress / mMaxProgress;
    mCurrentAngleSize = (int) (mAngleSize * size);
    setAnimator(0, mCurrentAngleSize);
}

/**
 * 設(shè)置進(jìn)度圓弧的顏色
 *
 * @param color
 */
public void setProgressColor(int color) {
    if (color == 0) {
        throw new IllegalArgumentException("Color can no be 0");
    }
    mProgressColor = color;
}

/**
 * 設(shè)置圓弧的顏色
 *
 * @param color
 */
public void setArcBgColor(int color) {
    if (color == 0) {
        throw new IllegalArgumentException("Color can no be 0");
    }
    mArcBgColor = color;
}

/**
 * 設(shè)置圓弧的寬度
 *
 * @param strokeWidth
 */
public void setStrokeWidth(int strokeWidth) {
    if (strokeWidth < 0) {
        throw new IllegalArgumentException("strokeWidth value can not be less than 0");
    }
    mStrokeWidth = dp2px(strokeWidth);
}

/**
 * 設(shè)置動畫的執(zhí)行時長
 *
 * @param duration
 */
public void setAnimatorDuration(long duration) {
    if (duration < 0) {
        throw new IllegalArgumentException("Duration value can not be less than 0");
    }
    mDuration = duration;
}

/**
 * 設(shè)置第一行文本
 *
 * @param text
 */
public void setFirstText(String text) {
    mFirstText = text;
}

/**
 * 設(shè)置第一行文本的顏色
 *
 * @param color
 */
public void setFirstTextColor(int color) {
    if (color <= 0) {
        throw new IllegalArgumentException("Color value can not be less than 0");
    }
    mFirstTextColor = color;
}

/**
 * 設(shè)置第一行文本的大小
 *
 * @param textSize
 */
public void setFirstTextSize(float textSize) {
    if (textSize <= 0) {
        throw new IllegalArgumentException("textSize can not be less than 0");
    }
    mFirstTextSize = textSize;
}

/**
 * 設(shè)置第二行文本
 *
 * @param text
 */
public void setSecondText(String text) {
    mSecondText = text;
}

/**
 * 設(shè)置第二行文本的顏色
 *
 * @param color
 */
public void setSecondTextColor(int color) {
    if (color == 0) {
        throw new IllegalArgumentException("Color value can not be less than 0");
    }
    mSecondTextColor = color;
}

/**
 * 設(shè)置第二行文本的大小
 *
 * @param textSize
 */
public void setSecondTextSize(float textSize) {
    if (textSize <= 0) {
        throw new IllegalArgumentException("textSize can not be less than 0");
    }
    mSecondTextSize = textSize;
}

/**
 * 設(shè)置圓弧開始的角度
 *
 * @param startAngle
 */
public void setStartAngle(int startAngle) {
    mStartAngle = startAngle;
}

/**
 * 設(shè)置圓弧的起始角度到終點角度的大小
 *
 * @param angleSize
 */
public void setAngleSize(int angleSize) {
    mAngleSize = angleSize;
}

/**
 * dp轉(zhuǎn)成px
 *
 * @param dp
 * @return
 */
private int dp2px(float dp) {
    float density = getResources().getDisplayMetrics().density;
    return (int) (dp * density + 0.5f * (dp >= 0 ? 1 : -1));
}

/**
 * 設(shè)置動畫
 *
 * @param start  開始位置
 * @param target 結(jié)束位置
 */
private void setAnimator(float start, float target) {
    ValueAnimator valueAnimator = ValueAnimator.ofFloat(start, target);
    valueAnimator.setDuration(mDuration);
    valueAnimator.setTarget(mCurrentAngleSize);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            mCurrentAngleSize = (float) valueAnimator.getAnimatedValue();
            invalidate();
        }
    });
    valueAnimator.start();
}

/**
 * 測量字體的高度
 *
 * @param textStr
 * @param fontSize
 * @return
 */
private float getFontHeight(String textStr, float fontSize) {
    Paint paint = new Paint();
    paint.setTextSize(fontSize);
    Rect bounds = new Rect();
    paint.getTextBounds(textStr, 0, textStr.length(), bounds);
    return bounds.height();
}

}

然后是具體使用控件里面的代碼:

<com.amos.customview.ArcProgressBar
    android:id="@+id/arc"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_gravity="center"/>

這里使用非常簡單,跟其它控件的使用沒什么區(qū)別。

里面還定義了很多直接在xml文件里面就可以直接設(shè)置的屬性

<declare-styleable name="ArcProgressBar">
    <attr name="arc_max_progress" format="float"/>
    <attr name="arc_bg_color" format="color"/>
    <attr name="arc_stroke_width" format="dimension"/>
    <attr name="arc_progress" format="float"/>
    <attr name="arc_progress_color" format="color"/>
    <attr name="arc_first_text" format="string"/>
    <attr name="arc_first_text_color" format="color"/>
    <attr name="arc_first_text_size" format="dimension"/>
    <attr name="arc_second_text" format="string"/>
    <attr name="arc_second_text_color" format="color"/>
    <attr name="arc_second_text_size" format="dimension"/>
    <attr name="arc_angle_size" format="float"/>
    <attr name="arc_start_angle" format="float"/>
</declare-styleable>

這個自定義View非常簡單,代碼里面注釋也寫的很清楚了,就不做過多的介紹了,有興趣的可以去做更多的擴(kuò)展,比如,直接做成圓形或者扇形,還有這里必須要兩行文本,如果項目需要,也可以直接去刪除掉文本,不過需要計算一下文本的繪制位置。

有興趣的可以去GitHub上面給個Start,地址是:傳送門

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

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,765評論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,046評論 4 61
  • 聽說北方都下雪了,南方下點小雨吧,終于漸漸有了涼意。 走在濕噠噠的小路上,一陣涼風(fēng)徐來,不經(jīng)打了個寒顫。心里卻升起...
    紫JZZ閱讀 286評論 1 3
  • 像山里的燈火 在孤獨和閃爍 夜是沉默的 把長長的河浸了透 同石頭一樣黢黑 一樣堅硬得冷酷 風(fēng)兒沒有憂傷 在大地上東...
    青木西閱讀 362評論 0 0
  • 最先想來學(xué)彩鉛是源于卡卡西在朋友圈里發(fā)的學(xué)員畫的圖,第一眼就喜歡冰淇淋和棉花糖,畫得香甜軟糯 雖然畫的還不完美 所...
    葉子醬醬閱讀 320評論 0 1

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