Andorid 自定义ProgressBar控件

很简单,首先加载Drawable,在onMeasure设置好其区域大小,
然后使用canvas.clipRect绘图

public class ProgressView extends ImageView {

    private Drawable maskDraw;

    /** * 加载的进度 0-100 */
    private int mProcess = 20;

    public ProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        maskDraw = context.getResources().getDrawable(R.drawable.red_bg);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 保存当前画笔的状态
        canvas.save();

        int topline = (int) (getHeight() - getHeight() * getProcess() / 100);
        /* * canvas 剪切出一个区域,使在这个区域里面的内容是有效的,区域之外是无效的。 */
        canvas.clipRect(0, topline, getWidth(), getHeight());

        maskDraw.draw(canvas);

        // 恢复到之前保存的状态
        canvas.restore();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        maskDraw.setBounds(0, 0, getWidth(), getHeight());
    }

    public float getProcess() {
        return mProcess;
    }

    /** * 设置新的进度以后,自动刷新 */
    public void setProgress(int mProcess) {
        if (mProcess > 100) {
            this.mProcess = 100;
        }
        if (mProcess < 0) {
            this.mProcess = 0;
        }

        this.mProcess = mProcess;
        invalidate();
    }

}

使用方法

public class ProgressActivity extends Activity {

    private ProgressView piv;

    private int pivDeep = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progressview);

        piv = (ProgressView) findViewById(R.id.my_pro_iv);

        handler.sendEmptyMessage(2);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                piv.setProgress(pivDeep);
                break;
            case 2:
                new Thread() {
                    public void run() {
                        while (true) {

                            pivDeep = (pivDeep + 5) % 100;

                            handler.sendEmptyMessage(1);
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                }.start();

                break;

            default:
                break;
            }
        }

    };

}

你可能感兴趣的:(控件)