簡單自定義水平的ProgressBar帶文字
阿新 • • 發佈:2019-01-09
首先來看看實圖
這裡實現原理就是繼承ProgressBar重寫onDraw方法,在ondraw裡面用畫筆繪製text
首先初始化paint
首先獲取手機螢幕的寬高,根據手機解析度來定標準字型大小,這裡採用的720x1080(比較通用)
獲取進度,設定文字內容
最後就是onDraw繪製了
@Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); Rect rect = new Rect(); this.mPaint.getTextBounds(text, 0, text.length(), rect); this.mPaint.getTextBounds(text1, 0, text1.length(), rect); int progress = getProgress(); int width = getWidth();
/**以免getmax為0
if (getMax() != 0) { int start = width / getMax() * progress; int end = width / getMax() * (getMax() - progress); intx_two = ((end / 2) + start) - rect.centerX(); int x_one = (start / 2) - rect.centerX(); int y = (getHeight() / 2) - rect.centerY(); if (getProgress() == 0) { canvas.drawText(this.text1, x_two, y, this.mPaint); } else { canvas.drawText(this.text, x_one, y, this.mPaint); canvas.drawText(this.text1, x_two, y, this.mPaint); } } }
到這裡就完成了。
程式碼下載地址http://download.csdn.net/download/lmy545x/10038852