wxr
2022-11-24 2af932533ef851bf983385244e9912976dbd4daa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.lechange.demo.view;
 
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ProgressBar;
 
import com.lechange.demo.R;
 
public class LcProgressBar extends ProgressBar {
 
    private final Paint progressPaint = new Paint();
    private Context context;
    private String content = getResources().getString(R.string.lc_demo_device_update);
    private int textColor = getResources().getColor(R.color.lc_demo_color_0B8C0D);
 
    public LcProgressBar(Context context) {
        this(context, null);
    }
 
    public LcProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
 
    public LcProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
    }
 
    private void init() {
        progressPaint.setStrokeWidth(4);
        progressPaint.setStyle(Paint.Style.FILL);
        progressPaint.setColor(textColor);
        progressPaint.setTextSize(dip2Px(context.getResources().getDimensionPixelSize(R.dimen.px_12)));
        progressPaint.setTextAlign(Paint.Align.CENTER);
        progressPaint.setAntiAlias(true);
    }
 
    private int dip2Px(int dip) {
        float density = context.getResources().getDisplayMetrics().density;
        int px = (int) (dip * density + 0.5f);
        return px;
    }
 
    @Override
    protected synchronized void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Rect rect = new Rect();
        progressPaint.getTextBounds(this.content, 0, this.content.length(), rect);
        int x = (getWidth() / 2) ;
        int y = (getHeight() / 2) - rect.centerY();
        canvas.drawText(this.content, x, y, this.progressPaint);
    }
 
    public void setText(String text) {
        this.content = text;
        postInvalidate();
    }
 
    public String  getText(){
        return content;
    }
 
    public void setTextColor(int color) {
        this.textColor = color;
        progressPaint.setColor(textColor);
        postInvalidate();
    }
}