我正在试图弄清楚如何使用Canvas在一个大的白色表面上绘制一个小图形(并不重要)。问题是,如果我从一个大的空Bitmap开始,当我使用ARGB_8888制作一个可变副本时,Android会立即耗尽内存。我很好奇我是否遗漏了某些东西,或者由于Android中的内存限制,实际上无法将小图形合成到大的白色表面并将其保存为PNG或JPG。
答案 0 :(得分:6)
当然,当你想要创建巨大的位图时,你会受到内存的限制,但是你有足够的内存来创建相当大的位图。例如,1024 * 1024 ARGB_8888位图将需要大约4 MB的内存,如果您的应用程序通常节省内存,这不是问题。 Android应用程序的正常堆大小通常在16-32 MB之间,具体取决于Android版本,只是为了让您感受到您必须使用的内容。
你说你制作了大型位图的副本,这可能是你的主要问题。无需复制大型位图,只需要一个。这是一个示例项目,它创建一个大的(1024 * 1024)白色位图,并在您的应用程序中间绘制一个View,然后将结果写入PNG:
package com.example.android;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class WhitePngActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.draw_to_bitmap).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bitmap largeWhiteBitmap = Bitmap.createBitmap(1024, 1024, Bitmap.Config.ARGB_8888);
// Make a canvas with which we can draw to the bitmap
Canvas canvas = new Canvas(largeWhiteBitmap);
// Fill with white
canvas.drawColor(0xffffffff);
// Draw the view to the middle of the big white bitmap. In this
// case, it will be the button, but you can draw any View in
// your view hierarchy to the bitmap like this. And of course
// you can position the View anywhere you want
canvas.save();
canvas.translate(
largeWhiteBitmap.getWidth() / 2 - view.getWidth() / 2,
largeWhiteBitmap.getHeight() / 2 - view.getHeight() / 2);
view.draw(canvas);
canvas.restore();
// Write the file (don't forget android.permission.WRITE_EXTERNAL_STORAGE)
File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File pngFile = new File(pictureDir, "big-white-image-with-view.png");
try {
largeWhiteBitmap.compress(Bitmap.CompressFormat.PNG, 0, new FileOutputStream(pngFile));
} catch (FileNotFoundException e) {
Log.e("WhitePngActivity", "Could not write " + pngFile, e);
}
// Immediately release the bitmap memory to avoid OutOfMemory exception
largeWhiteBitmap.recycle();
}
});
}
}
与这个主要布局一起:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/draw_to_bitmap"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click to draw to bitmap" />
</LinearLayout>
你会得到像/mnt/sdcard/Pictures/big-white-image-with-view.png
这样的位图,如下所示: