您好我想将String转换为Bitmap并且一切都很好但我不知道如何设置结果Image以适合文本。 我怎样才能做到这一点 ? 这是我的代码:
public Bitmap textAsBitmap(String text, float textSize, float stroke,
int color, Typeface typeface) {
TextPaint paint = new TextPaint();
paint.setColor(color);
paint.setTextSize(textSize);
paint.setStrokeWidth(stroke);
paint.setTypeface(typeface);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = (int) (-paint.ascent() + 3f);
StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
1.0f, false);
int linecount = staticLayout.getLineCount();
int height = (int) (baseline + paint.descent() + 3) * linecount + 10;
Bitmap image = Bitmap
.createBitmap(****MY WIDTH***, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);
staticLayout.draw(canvas);
return image;
}
我甚至试过这个,但它没有正常工作:
final Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
Bitmap image = Bitmap
.createBitmap(bounds.width(), height, Bitmap.Config.ARGB_8888);
请帮忙!
答案 0 :(得分:0)
试试这个:
canvas.drawColor(Color.BLUE);
而不是:
canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);
答案 1 :(得分:0)
你应该尝试这个
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArray);
byte[] b = byteArray.toByteArray();
String result = Base64.encodeToString(b, Base64.DEFAULT);
return result;
}
希望这会有所帮助!!!