android - 无法根据 android 中的给定文本对齐可绘制矩形坐标?

标签 android android-canvas android-drawable android-bitmap

我想在给定的 text 上绘制一个矩形作为透明 Canvas ,如下图所示: enter image description here

我正在使用以下代码绘制透明矩形但无法理解坐标位置。我尝试了很多时间,但没有用。

canvas.drawRect(left,top,right,bottom,paint);

这是我的代码:

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);
paint.setAlpha(255);
rectPaint.setAlpha(100);
canvas.drawText("$250", 20, 400, paint);
canvas.drawBitmap(bitmapImage, 490, 55, null);
canvas.drawRect(0, 100, 300, 400, rectPaint);

drawRect 方法中其余坐标的值是多少,以将其对齐为 text 的给定 coordinates。现在我正在使用

canvas.drawRect(0, ? , ? , ?, rectPaint);   

最佳答案

您可以为此使用 Paint.getTextBounds() 方法。

getTextBounds(String text, int start, int end, Rect bounds)

Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

这将为您提供所需的 Rect,然后您需要使用随 drawText 提供的坐标偏移此 Rect打电话。

关于android - 无法根据 android 中的给定文本对齐可绘制矩形坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693953/

相关文章:

android - 使用 volley 的 HTTPS 请求

android - 为什么此页面不适合屏幕?

android - onPreviewFrame 和异常锁定表面

具有弯曲边缘的Android矩形

android - 我在负重方面做错了什么?

java - Canvas 如何确定其裁剪范围?

java - Android Canvas : make a drawn line fade/alphaAnimation away on touch

Android从不同的资源文件夹中挑选图像和样式

android - 可绘制对象中不能有多个文件夹吗?

android - java.lang.NoSuchMethodError : No static method setOnApplyWindowInsetsListener