相關代碼請參閱: github.com/RustFisher/…java
美工同窗指定了一個進度條樣式android
這斑斕的進度條,若是要本身畫實在是勞民傷財。因而請美工切了一張素材(樣例)。git
若是用shape或者.9圖片不太好處理這個條紋。轉變思路,放置2張圖片。一張做爲背景(底,bottom),一張做爲進度條圖片(cover)。 進度改變時,改變上面圖片的寬度。github
這就要求上面的圖片是圓角的。自定義ImageView,調用canvas.clipPath
來切割畫布。canvas
public class RoundCornerImageView extends android.support.v7.widget.AppCompatImageView {
private float mRadius = 18;
private Path mClipPath = new Path();
private RectF mRect = new RectF();
public RoundCornerImageView(Context context) {
super(context);
}
public RoundCornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundCornerImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setRadiusDp(float dp) {
mRadius = dp2px(dp, getResources());
postInvalidate();
}
public void setRadiusPx(int px) {
mRadius = px;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
mRect.set(0, 0, this.getWidth(), this.getHeight());
mClipPath.reset(); // remember to reset path
mClipPath.addRoundRect(mRect, mRadius, mRadius, Path.Direction.CW);
canvas.clipPath(mClipPath);
super.onDraw(canvas);
}
private float dp2px(float value, Resources resources) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, resources.getDisplayMetrics());
}
}
複製代碼
每次繪製都切割一次圓角。記得調用Path.reset()
方法。app
回到咱們要的進度條。佈局文件中放置好層疊的圖片。ide
<RelativeLayout android:id="@+id/progress_layout" android:layout_width="190dp" android:layout_height="10dp" android:layout_centerInParent="true">
<ImageView android:id="@+id/p_bot_iv" android:layout_width="190dp" android:layout_height="10dp" android:src="@drawable/shape_round_corner_bottom" />
<com.rustfisher.view.RoundCornerImageView android:id="@+id/p_cover_iv" android:layout_width="100dp" android:layout_height="10dp" android:scaleType="centerCrop" android:src="@drawable/pic_cover_blue_white" />
</RelativeLayout>
複製代碼
須要在代碼中動態地改變cover的寬度;dialog中提供以下方法改變LayoutParams
佈局
public void updatePercent(int percent) {
mPercent = percent;
mPercentTv.setText(String.format(Locale.CHINA, "%2d%%", mPercent));
float percentFloat = mPercent / 100.0f;
final int ivWidth = mBotIv.getWidth();
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mProgressIv.getLayoutParams();
int marginEnd = (int) ((1 - percentFloat) * ivWidth);
lp.width = ivWidth - marginEnd;
mProgressIv.setLayoutParams(lp);
mProgressIv.postInvalidate();
}
複製代碼
顯示出dialog並傳入進度,就能夠看到效果了。post
這只是實現效果的一種方法,若是有更多的想法,歡迎和我交流~this