问题
I have a progress bar with text in which I have overridden the onDraw like so:
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
float fx = getX();
float fy = getY();
int x = getWidth() / 2 - bounds.centerX();
int y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}
I am trying to position the text inside of the secondary progress but not really sure how get the the current width of the secondary progress, basically the width of the current progress.
回答1:
For now I just used a work around, basically I get the percentage of the progress and then multiply it by the density. I needed to align the text 20dp within the progress bar:
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(textColor);
textPaint.setTextSize(textSize);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
float density = getContext().getResources().getDisplayMetrics().density;
float percentage = getProgress() / 100.0f;
float x = getWidth() * percentage - (20 * density);
float y = getHeight() / 2 - bounds.centerY();
canvas.drawText(text, x, y, textPaint);
}
来源:https://stackoverflow.com/questions/13918947/get-the-width-of-a-the-secondaryprogress-within-a-android-progressbar