渐变进度条

来源:互联网 发布:淘宝皇冠和天猫哪个好? 编辑:程序博客网 时间:2024/05/18 01:03

用创建图片的方式来写渐变的进度条:
public class MyProgressView extends ViewGroup {

/** * 进度条当前值 */private float currentCount = 4.8f;private int mWidth, mHeight;public MyProgressView(Context context) {    this(context, null);}public MyProgressView(Context context, AttributeSet attrs) {    super(context, attrs);    setWillNotDraw(false);}@Overrideprotected void onLayout(boolean b, int i, int i1, int i2, int i3) {    //}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);    if (widthSpecMode == MeasureSpec.EXACTLY || widthSpecMode == MeasureSpec.AT_MOST) {        mWidth = widthSpecSize;    } else {        mWidth = 0;    }    if (heightSpecMode == MeasureSpec.EXACTLY || heightSpecMode == MeasureSpec.AT_MOST) {        mHeight = heightSpecSize;    } else {        mHeight = 0;    }    setMeasuredDimension(mWidth, mHeight);}@Overrideprotected void onDraw(Canvas canvas) {    super.onDraw(canvas);    //初始化画笔    /*  画笔 */    Paint mPaint = new Paint();    mPaint.setAntiAlias(true);    //画矩形背景    setBackgroundResource(R.drawable.shape_evaluate_grade_bg);    Drawable drawable = getBackground();    if (drawable == null) {        return;    }    /*  进度条最大值 */    float maxCount = 5;    float progress = currentCount / maxCount;    //切取图片    Drawable drawable1 = getResources().getDrawable(R.drawable.shape_evaluate_grade_bg_3);    Bitmap bmp = drawableToBitamp(drawable1);    //这里需要处理高度大于0的问题,当高度为0的时候就不去绘制前景    if (progress > 0) {        Bitmap bmp2 = Bitmap.createBitmap(bmp, 0, (int) (mHeight - mHeight * progress + 0.5), (int) (mWidth + 0.5), (int) (progress * mHeight + 0.5));        BitmapShader mBitmapShader = new BitmapShader(bmp2, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);        mPaint.setShader(mBitmapShader);        canvas.drawBitmap(bmp2, 0, mHeight - progress * mHeight, mPaint);    }}/** * drawable转bitmap * * @param drawable * @return */private Bitmap drawableToBitamp(Drawable drawable) {    if (drawable instanceof BitmapDrawable) {        BitmapDrawable bd = (BitmapDrawable) drawable;        return bd.getBitmap();    }    int w = getWidth();    int h = getHeight();    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);    Canvas canvas = new Canvas(bitmap);    drawable.setBounds(0, 0, w, h);    drawable.draw(canvas);    return bitmap;}public void setProgress(float f) {    currentCount = f;    invalidate();}@Overridepublic void onWindowFocusChanged(boolean hasWindowFocus) {    super.onWindowFocusChanged(hasWindowFocus);    invalidate();}

}

原创粉丝点击