2012-01-19 160 views
0

我正在使用以下代碼片段來創建帶有文本的位圖。確定位圖的寬度和高度

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
paint.setStyle(Style.FILL); 
paint.setColor(fontColor); 
paint.setTextSize(fontSize); 
canvas.drawText("My Text", x, y, paint); 

這裏有一個問題。如何預先確定在畫布中使用的位圖的大小?例如,如果我想要一個帶有「Hello World!」的位圖在它上面,甚至在畫布上繪製文本之前,我想找到它的寬度和高度。

+0

檢查這裏更換bitmap: http://stackoverflow.com/questions/4552833/how-to-get-width-and-height-of-the-image – petey

+0

怎麼轉換位圖變成可繪製的,然後得到可繪製的寬度和高度? –

回答

1

您可以TYR此:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 

Rect bounds = new Rect(); 

paint.setStyle(Style.FILL); 
paint.setColor(fontColor); 
paint.setTextSize(fontSize); 

paint.getTextBounds("My Text", 0, "My Text".length(), bounds); 

int width = bounds.width(); 
int height = bounds.height(); 

canvas.drawText("My Text", x, y, paint); 
1

試試這個,它加載的位圖,然後得到heigth和寬度,然後你只需要繪製它。用你的形象的名字

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap); 
bitmapHeigth = bitmap.getHeigth(); 
bitmapWidth = bitmap.getWidth();