在ImageView中绘制文本

时间:2012-07-25 08:15:29

标签: android canvas

我在ImageView中有一个Nine-Patch Image,想要将文本绘制到图像的内容区域。 Android将拉伸图像,在不同的屏幕上,我无法使用像dp或px这样的单位。这太不准确了。

如何完成这项任务? =)

1 个答案:

答案 0 :(得分:3)

您可以编写自定义ImageView,在onDraw(Canvas canvas)方法中,您可以通过以下方式在其上绘制文字:

Paint paint = new Paint()
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.BLACK);
paint.setTextSize(11);
canvas.drawText("your text", x, y, paint);

您可以将文字置于ImageView的中心位置,例如:

int imgWidth = getMeasuredWidth();
int imgHeight = getMeasuredHeight();
float txtWidth = paint.measureText("your text");

int x = imgWidth/2 - txtWidth/2;
int y = imgHeight/2 - 6; // 6 is half of the text size
相关问题