你好!
是否存在以下问题:我需要在相当大的图像上写一个长文本并将其保存在那里。
条件:
options.inSampleSize = 10;
并且没有内存不足的问题当前问题:
当我尝试在Bitmap中加载此图像时,会出现内存限制(VM预算)错误。
问题:
代码示例:
// Step 1. Open image and load to Bitmap
Bitmap bitmap = BitmapFactory.decodeFile(fileName); // runtime Exception like "VM budget" !
// or
//Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.big_img_1); // as in previous runtime Exception like "VM budget" !
// or
//Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream); // as in previous runtime Exception like "VM budget" !
// Step 2. Write text
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(14);
Canvas canvas = new Canvas(bitmap);
canvas.drawText("some long long string over all image", 100, 100, paint);
// Step 3. Save bitmap to file
OutputStream fOut = new FileOutputStream(new File(fileName));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
/*
_________________________________________________
| |
| |
| |
| |
| IMG |
| |
| |
| some long long string over all image |
|________________________________________________|
*/
答案 0 :(得分:1)
首先使用以下帮助加载大位图
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
其次要写入图像并保存,你可以使用画布
我在应用中做了类似的事情。使用画布。
我编辑了一段我的代码,实际上在背景上添加了几个其他图像。
代码肉:
private static Bitmap getPoster(...) {
Bitmap background = BitmapFactory.decodeResource(res, background_id)
.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(background);
Typeface font = Typeface.createFromAsset(res.getAssets(), FONT_PATH);
font = Typeface.create(font, Typeface.BOLD);
Paint paint = new Paint();
paint.setTypeface(font);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.BLACK);
float fontSize = getFontSize(background.getWidth(), THE_QUOTE, paint); //You'll have to define a way to find a size that fits, or just use a constant size.
paint.setTextSize(fontSize);
canvas.drawText(THE_QUOTE, (background.getWidth() - paint.measureText(THE_QUOTE)) / 2,
background.getHeight() - FILLER_HEIGHT, paint); //You might want to do something different. In my case every image has a filler in the bottom which is 50px.
return background;
}
将您自己的版本放在一个类中,并为其提供图像ID和其他任何内容。它会返回一个位图,供您随意使用(在imageview中显示,让用户保存并设置为wallpape)。
答案 1 :(得分:1)
这不是您正在寻找的,但它可能会有所帮助。
如果您的图片不透明,您可以通过为其配置指定RGB_565来减少加载它所需的内存量:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);