使用 LinearGradient 漸變色的進度條
阿新 • • 發佈:2019-01-05
- 建構函式
public LinearGradient(float x0, float y0, float x1, float y1,int color0, int color1, TileMode tile)
public LinearGradient(float x0, float y0, float x1, float y1,int colors[], float positions[], TileMode tile)
// color0 color1這是一個對兩個顏色的著色
// x0,y0 起始點 x1 ,y1 結束點
使用只需要 mPaint.setShader(shader);
下面用他實現一個漸變色的進度條帶有動畫效果
public class LinerProgressView extends View {
/** * 漸變顏色段 */ private static final int[] SECTION_COLORS = {Color.RED, Color.GREEN, Color.BLUE}; private float maxCount = 100; private float currentCount = 30; private Paint mPaint; private int mWidth, mHeight; private RectF rectBg = new RectF(); // 外框背景 private RectF rectProgressBg = new RectF();//進度條 private LinearGradient shader; public LinerProgressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } public LinerProgressView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public LinerProgressView(Context context) { super(context); initView(context); } private void initView(Context context) { mPaint = new Paint(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mHeight = bottom - top; mWidth = right - left; rectBg.set(0, 0, mWidth, mHeight); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (shader == null) { shader = new LinearGradient(0, 0, mWidth, mHeight, SECTION_COLORS, null, Shader.TileMode.CLAMP); } mPaint.setShader(shader); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); //繪製進度條外側邊框 int round = mHeight * 1 / 3; canvas.drawRoundRect(rectBg, round, round, mPaint); //繪製進度條 mPaint.setStyle(Paint.Style.FILL); float section = currentCount / maxCount; Log.i("currentCount","count:" + currentCount) ; int pl = (int) (mWidth * (section)); rectProgressBg.set(0, 0, pl, mHeight); canvas.drawRoundRect(rectProgressBg, round, round, mPaint); } /* * 設定最大的進度值 */ public void setMaxCount(float maxCount) { this.maxCount = maxCount; } /** * 設定當前的進度值 * 2s 的漸變動畫 變加速 */ public void setCurrentCount( float progress) { this.currentCount = progress > maxCount ? maxCount : progress; ValueAnimator animator = new ValueAnimator().ofFloat(0,progress); animator.setInterpolator( new AccelerateInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentCount = (float) animation.getAnimatedValue(); postInvalidate(); } }); animator.setDuration(2000); animator.start(); } public float getMaxCount() { return maxCount; } public float getCurrentCount() { return currentCount; }
}
“`