2017-01-22 65 views
1

我需要在水平和垂直居中的位圖中繪製文本,調整文本大小以覆蓋所有空間。問題是文本是多行的\n。這是我當前的代碼:Canvas drawtext multiline居中

private int determineMaxTextSize(String str, float maxWidth) { 
     int size = 0; 
     if (TextUtils.isEmpty(str)) 
      return 0; 
     Paint paint = new Paint(); 
     do { 
      paint.setTextSize(++size); 
     } while (paint.measureText(str) < maxWidth); 
     return size > 0 ? size - 1 : 0; 
    } 

private void drawText(String text, int textColor, int bckColor) { 
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 
    int max = Integer.MAX_VALUE; 
    String[] tokens = text.split("\n"); 
    for (String s : tokens) { 
     int m = determineMaxTextSize(s, params.width); 
     if (m > 0 && m < max) 
      max = m; 
    } 
    paint.setTextSize(max); 
    paint.setColor(textColor); 
    paint.setTextAlign(Paint.Align.CENTER); 
    Bitmap b = Bitmap.createBitmap(params.width + 1, params.height + 1, Bitmap.Config.ARGB_8888); 
    b.eraseColor(bckColor); 
    Canvas canvas = new Canvas(b); 
    Rect r = new Rect(); 
    int xPos = canvas.getWidth()/2; 
    int yPos = (canvas.getHeight()/2); 
    for (String s : tokens) { 
     if (s.equals("\n")) 
      s = " "; 
     paint.getTextBounds(s, 0, s.length(), r); 
     canvas.drawText(s, xPos, yPos, paint); 
     yPos += Math.abs(r.height()); 
    } 
    setImageBitmap(b); 
} 

此代碼幾乎可以工作,但文本從中心開始。

回答

1

這是一個遲到的答案,所以我很抱歉,如果它不再需要,但在尋找答案後,我決定聘請一些數學來解決這個問題。

爲了以我的多行文本爲中心,我取了畫布的寬度,減去文本的寬度,然後除以2.然後使用此數字作爲drawText方法的x偏移量。

這是我的完整的例子:

public static Bitmap textAsBitmap(String text, float textSize, int textColor, Context mContext) { 
    Paint paint = new Paint(ANTI_ALIAS_FLAG); 
    int pixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, textSize, mContext.getResources().getDisplayMetrics()); 

    String[] str = text.split(","); 

    paint.setTextSize(pixel); 
    paint.setTypeface(FontUtils.getRalewayExtraBold(mContext)); 
    paint.setColor(textColor); 
    paint.setTextAlign(Paint.Align.LEFT); 
    float baseline = -paint.ascent(); // ascent() is negative 
    int width = (int) (paint.measureText(text) + 0.0f); // round 

    int height = (int) (baseline + paint.descent() + 0.0f); 
    Bitmap image = Bitmap.createBitmap((width/str.length)+10, (height*str.length), Bitmap.Config.ARGB_8888); 

    Canvas canvas = new Canvas(image); 

    for (int i = 0; i < str.length; i++){ 
     //Center text here 
     float textOffset = (canvas.getWidth()-paint.measureText((str[i])))/2; 
     canvas.drawText(str[i], textOffset, ((i+1)*baseline), paint); 
    } 

    return image; 
}