获取 Android ProgressBar 中 secondaryProgress 的宽度

2023-12-25

我有一个带有文本的进度条,其中我已经重写了 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 Android ProgressBar 中 secondaryProgress 的宽度 的相关文章

随机推荐