Android 绘制反色文字进度条

一直想要实现一个这样的效果,终于弄出来了做个记录。

public class MyProgressView extends View {

    private Paint mPaint;

    private int viewWidth, viewHeight;

    private float maxProgress = 100;

    private float progress = 0;

    private Bitmap progressBitmap, textBitmap;

    private Canvas proCanvas, textCanvas;

    private RectF dstRect, srcRect;

    private Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.XOR);

    public MyProgressView(Context context) {
        this(context, null);
    }

    public MyProgressView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(100);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
        progressBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        textBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        proCanvas = new Canvas(progressBitmap);
        textCanvas = new Canvas(textBitmap);
        srcRect = new RectF(0, 0, w, h);
        dstRect = new RectF(0, 0, w, h);
    }

    public MyProgressView setMaxProgress(float maxProgress) {
        this.maxProgress = maxProgress;
        return this;
    }

    public void setProgress(float progress) {
        this.progress = progress;
        proCanvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
        mPaint.setColor(Color.BLUE);
        proCanvas.drawRect(0, 0, viewWidth * (progress / maxProgress), viewHeight, mPaint);
        String text = String.format(Locale.getDefault(), "%.2f%%", progress);
        mPaint.setColor(Color.RED);
        Paint.FontMetrics metrics = mPaint.getFontMetrics();
        float fontHeight = metrics.bottom - metrics.top;
        float textBaseY = viewHeight - (viewHeight - fontHeight) / 2 - metrics.bottom;
        textCanvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
        textCanvas.drawText(text, (viewWidth - mPaint.measureText(text)) / 2, textBaseY, mPaint);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int saveCount = canvas.saveLayer(srcRect, mPaint, Canvas.ALL_SAVE_FLAG);
        //这里先绘制底部的进度条
        canvas.drawBitmap(progressBitmap, null, srcRect, mPaint);
        //设置混合模式
        mPaint.setXfermode(xfermode);
        //在回事文本
        canvas.drawBitmap(textBitmap, null, dstRect, mPaint);
        mPaint.setXfermode(null);
        canvas.restoreToCount(saveCount);
    }
}

猜你喜欢

转载自blog.csdn.net/zgy441008825/article/details/90315276
今日推荐