android 自定義ProgressBar 文字跟隨進度效果
阿新 • • 發佈:2019-01-22
1 字型適配
private void textSizeAdaptive() { //1.獲取當前裝置的螢幕大小 DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); //2.計算與你開發時設定的螢幕大小的縱橫比(這裡假設你開發時定的螢幕大小是480*800) int screenWidth = displayMetrics.widthPixels; int screenHeight = displayMetrics.heightPixels; float ratioWidth = (float) screenWidth / 1080; float ratioHeight = (float) screenHeight / 1920; ratio = Math.min(ratioWidth, ratioHeight); if (ratioWidth != ratioHeight) { if (ratio == ratioWidth) { offsetLeft = 0; offsetTop = Math.round((screenHeight - 1920 * ratio) / 2); } else { offsetLeft = Math.round((screenWidth - 1080 * ratio) / 2); offsetTop = 0; } } //3.根據上一步計算出來的最小縱橫比來確定字型的大小(假定在1080*1920螢幕下字型大小設定為35) TEXT_SIZE = Math.round(textsize * ratio); }
- onDraw
@Override protected synchronized void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.save(); mText = (getProgress() * 100 / getMax()) + "%"; Rect rect = new Rect(); mPaint.getTextBounds(leftText, 0, leftText.length(), rect); int y = (getHeight() / 2) - rect.centerY(); //在進度條上畫上自定義文字 canvas.drawText(leftText, 5, y, mPaint); int width = rect.width(); //進度 float radio = getProgress() * 1.0f / getMax(); float progressPosX = (int) (mRealWidth * radio); //起始點 int beginX = 10 + width; //結束點 float textWidth = mPaint.measureText(mText); float endX = mRealWidth - textWidth; if (beginX > progressPosX- textWidth) { canvas.drawText(mText, beginX, y, mPaint); } else if (progressPosX- textWidth > endX) { canvas.drawText(mText, endX, y, mPaint); } else { canvas.drawText(mText, progressPosX - textWidth, y, mPaint); } canvas.restore(); }