使用Canvas Android在填充的矩形内绘制文本 [英] Draw text inside a filled rectangle using Canvas Android
问题描述
如何绘制具有指定范围的填充矩形,并在要使用Canvas Android绘制的矩形文本内绘制该矩形?我尝试过
How to draw a filled rectangle with specified bounds and inside that rectangle text to be drawn using Canvas Android ?? I tried
mPaint.setColor(Color.GREEN);
canvas.drawText(mText, x, y, mPaint);
mPaint.setColor(Color.BLACK);
canvas.drawRect(x, y, x + w, y + h, mPaint);
但文本不在该矩形内。有什么伙伴可以告诉我如何在考虑文字大小的情况下在指定文字周围绘制矩形吗?
but text is not inside of that rectangle. Can any buddy tell me how to draw a rectangle surrounding specified text with consideration of text size ??
推荐答案
在这里,我对x和y值进行了硬编码。您可以更改它们
Here i have hardcoded x and y values. You can change them
mpaint= new Paint();
mpaint.setColor(Color.RED);
mpaint.setStyle(Style.FILL);
paint2= new Paint();
paint2.setColor(Color.GREEN);
paint2.setTextSize(50); //set text size
float w = paint2.measureText(s)/2;
float textSize = paint2.getTextSize();
@Override
protected void onDraw(Canvas canvas) {
paint2.setTextAlign(Paint.Align.CENTER);
canvas.drawRect(300-w, 300 - textsize, 300 + w, 300, mpaint);
canvas.drawText(s, 300, 300 ,paint2); //x=300,y=300
}
编辑:
在 onDraw
中调用 measureText
是一个好主意。您可以在 onDraw
之外进行此操作。
Its bad a idea to call measureText
in onDraw
. You can do that outside of onDraw
.
还有一个有关性能以及为什么要避免分配的视频。在 onDraw
中。 https://www.youtube.com/watch?v=HAK5acHQ53E
There is a video on also about performance and why you should avoid allocations in onDraw
. https://www.youtube.com/watch?v=HAK5acHQ53E
结果快照
这篇关于使用Canvas Android在填充的矩形内绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!