Nio*_*199 125 android text draw android-canvas
是否有一种方法可以根据用于绘制它的Paint使用drawText()方法返回要在Android画布上绘制的文本的宽度(以像素为单位)?
Mar*_*ein 215
你看过android.graphics.Paint.measureText(String txt)吗?
小智 31
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size
String text = "Some random text";
paint.getTextBounds(text, 0, text.length(), bounds);
text_height = bounds.height();
text_width = bounds.width();
Run Code Online (Sandbox Code Playgroud)
Sur*_*gch 11
补充答案
Paint.measureText
和和返回的宽度略有不同 Paint.getTextBounds
.measureText
返回一个宽度,其中包含填充字符串开头和结尾的字形的advanceX值.Rect
返回的宽度getTextBounds
没有此填充,因为边界是Rect
紧密包装文本的边界.
实际上有三种不同的测量文本的方法。
获取文本边界:
val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
paint.getTextBounds(contents, 0, 1, rect)
val width = rect.width()
Run Code Online (Sandbox Code Playgroud)
测量文本宽度:
val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val width = paint.measureText(contents, 0, 1)
Run Code Online (Sandbox Code Playgroud)
和 getTextWidths:
val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
val arry = FloatArray(contents.length)
paint.getTextBounds(contents, 0, contents.length, rect)
paint.getTextWidths(contents, 0, contents.length, arry)
val width = ary.sum()
Run Code Online (Sandbox Code Playgroud)
请注意,如果您尝试确定何时将文本换行到下一行,则 getTextWidths 可能很有用。
measureTextWidth 和 getTextWidth 是相等的,并且具有测量其他人发布的高级宽度。有些人认为这个空间过大。然而,这是非常主观的并且取决于字体。
例如,度量文本边界的宽度实际上可能看起来太小:
但是,当添加附加文本时,一个字母的边界看起来很正常:
图片取自Android Developers Guide to Custom Canvas Drawing
归档时间: |
|
查看次数: |
68226 次 |
最近记录: |