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);
}
此代碼幾乎可以工作,但文本從中心開始。