【发布时间】:2017-07-27 09:22:45
【问题描述】:
我有一个很长的字符串,我确信它不适合图像。所以我最终计算了行数,然后使用Canvas 在Bitmap 上逐行写入。问题是只写了第一行。我会一直写在这张图片上。每行的长度固定为 40 个字符。请检查以下代码:
private Bitmap prepareImageWithText(String text){
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.text_image); // Load your bitmap here
Bitmap aBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); // copy the bitmap because the one from the Resources is immutable.
Canvas canvas = new Canvas(aBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(75);
for(int i=0; i<calculateLines(text); i++) {
int beginFrom = i*40;
int endAt = beginFrom + 40;
if(endAt > text.length()){
endAt = text.length()-1;
}
String writableArea = text.substring(beginFrom, endAt);
canvas.drawText(writableArea, 100, 300+(i*100), paint);
canvas.save();
}
return aBitmap;
}
private int calculateLines(String text){
if(!TextUtils.isEmpty(text)){
int lines = text.length()/40;
return lines;
}
return 1;
}
【问题讨论】:
-
只需使用
android.text.Layout -
@pskink 你能解释一下吗?
-
@NaveenDissanayake
Math.roof?roof你在说什么?就算是Math.ceil,跟问题有什么关系? -
@NaveenDissanayake 啊好吧,我错过了他使用的是
i<calculateLines(text)而不是i<=calculateLines(text) -
只需使用
Layout只需两行安全代码,而不是几十行...