问题
I'm trying to create a bitmap from a view with this code :
public Bitmap getmyBitmap(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
But I have an Out Of Memory problems. I can fix it by adding this option to the Manifest file android:largeHeap="true" which is not recommended !!
I'm thinking about the recycle of the view ,could be a solution?
this is the printStack:
11-25 15:31:46.556 2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:46.616
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:46.666
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 4096016-byte allocation. 11-25 15:31:54.016
2115-2115/com.myproject.android E/dalvikvm-heap﹕ Out of memory on a 1879696-byte allocation. 11-25 15:31:54.016
2115-2115/com.myproject.android E/AndroidRuntime﹕ FATAL EXCEPTION: main
回答1:
I think you are getting a lot of Bitmaps which overloads your system memory, or if it a single one a think it's an extremely huge one, So, to solve the problem, you have to do two things, first make sure you don't run this method a lot of times for the same Bitmap
(as that leads to a lot of Bitmaps stored in your memory and all of them belonging to the same one), second use a custom method to scale your Bitmaps in order to lower it's size and hence it's memory occupation area:
// to scale your Bitmaps
// assign newWidth and newHeight with the corresponding width and height that doesn't make your memory overloads and in the same time doesn't make your image loses it's Features
public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) {
if(bitmapToScale == null)
return null;
//get the original width and height
int width = bitmapToScale.getWidth();
int height = bitmapToScale.getHeight();
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(newWidth / width, newHeight / height);
// recreate the new Bitmap and set it back
return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true);
}
来源:https://stackoverflow.com/questions/27132138/how-to-avoid-outofmemory-problems-with-create-bitmap