2012-07-25 100 views
1

我在ImageView中有一個Nine-Patch圖像,並且想要將文本繪製到圖像的內容區域。 Android會拉伸圖像,並在不同的屏幕上,我不能使用dp或px等單位。這太不準確了。在ImageView中繪製文本

如何完成此任務? =)

+1

使用帶背景的TextView作爲9patch圖像。 – 2012-07-25 08:39:25

回答

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 
+0

但是,我仍然有像素的問題,該文本不存在它應該是。 – 2012-07-25 08:23:31

+0

我用定位文本的簡單示例更新了我的答案。您不必擔心密度問題,因爲您始終使用實際的像素值計算位置。 – 2012-07-25 08:37:18

+0

由於性能的原因,不應在'OnDraw()'方法中設置'Paint'。對於需要使用TextUtils.ellipsize()來省略文本的情況,使用「TextPaint」而不是「Paint」也是一個好主意。 – Dennis 2014-02-20 10:12:52