我有一个带有文本的进度条,其中我覆盖了onDraw,如下所示:

@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);
}


我正在尝试将文本放置在辅助进度中,但不确定如何获取辅助进度的当前宽度,基本上是当前进度的宽度。

最佳答案

现在,我只是使用一种变通方法,基本上可以得到进度的百分比,然后乘以密度。我需要在进度栏中对齐文本20dp:

@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);
}

10-04 11:04