2012-03-28 58 views
5

我試圖在位圖的中心繪製文本,但是即使使用了align.center,我也無法做到。代碼是:位圖上的中心文本

public Bitmap drawTextToBitmap(Context gContext, String gText) { 
    Resources resources = gContext.getResources(); 
    float scale = resources.getDisplayMetrics().density; 
    Bitmap bitmap = 
      BitmapFactory.decodeResource(resources, R.drawable.blank_marker); 

    android.graphics.Bitmap.Config bitmapConfig = 
      bitmap.getConfig(); 
    // set default bitmap config if none 
    if(bitmapConfig == null) { 
     bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; 
    } 
    // resource bitmaps are imutable, 
    // so we need to convert it to mutable one 
    bitmap = bitmap.copy(bitmapConfig, true); 

    Canvas canvas = new Canvas(bitmap); 
    // new antialised Paint 
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    // text color - #3D3D3D 
    paint.setColor(Color.rgb(61, 61, 61)); 
    // text size in pixels 
    paint.setTextSize((int) (25 * scale)); 
    // text shadow 
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE); 

    // draw text to the Canvas center 
    Rect bounds = new Rect(); 
    paint.setTextAlign(Align.CENTER); 

    paint.getTextBounds(gText, 0, gText.length(), bounds); 
    int x = (bitmap.getWidth() - bounds.width())/2; 
    int y = (bitmap.getHeight() + bounds.height())/2; 

    canvas.drawText(gText, x * scale, y * scale, paint); 

    return bitmap; 
} 

我在做什麼錯?

+1

remove this paint.setTextAlign(Align.CENTER);並替換這個canvas.drawText(gText,x * scale,y * scale,paint);通過這個canvas.drawText(gText,x,y,paint);希望這會幫助 – Triode 2012-03-28 16:12:25

回答

12

這比您想象的要簡單得多。

Bitmap的寬度和高度(中心點)的一半處結合Paint.setTextAlign(Align.CENTER)繪製文本。

對齊屬性將負責其餘的。

+0

哇,永遠不會知道這個標誌。真棒小費! – Anton 2013-08-30 22:18:03

+0

偉大的答案:) – Madhu 2015-06-18 07:48:31

0

文字繪圖在哪裏?這個問題可能是因爲你將文本對齊到Align.CENTER。我相信,計算x和y的代碼假定文本渲染使用Align.LEFT。

在實際位圖中心使用setTextAlign(Align.CENTER)並渲染,或使用setTextAlign(Align.LEFT)並使用當前使用的x和y計算。

1

我想上面給出的答案都不夠好,所以我張貼我的答案。試一試吧,它可以在所有設備上工作,並且根本不復雜:

Canvas canvas = new Canvas(bitmap); 

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    //paint.setTextAlign(Align.CENTER); 
    paint.setColor(activity.getResources().getColor(R.color.white)); 
    paint.setTextSize(30); 

    // draw text to the Canvas center 
    Rect boundsText = new Rect(); 
    paint.getTextBounds(String.valueOf(cluster.getMarkerList().size()), 
      0, String.valueOf(cluster.getMarkerList().size()).length(), 
      boundsText); 
    int x = (bitmap.getWidth() - boundsText.width())/2; 
    int y = (bitmap.getHeight() + boundsText.height())/2; 

    canvas.drawText(String.valueOf(cluster.getMarkerList().size()), x, 
      y, paint); 
+0

這幾乎是正確的,但它不適用於「我」,「1」,「。」,... - 這些將在左側更多,並將在「 - 」(會稍微偏左,中間偏高)。嘗試使用 canvas.drawText(text,x - bounds.left,y - bounds.bottom,paint);那麼文字會真的在中間。 – 2014-11-28 09:48:18

+0

將x和y傳遞到drawText方法是最好的方法。謝謝! – Azrael94 2016-04-28 17:59:06