Issue
I'm trying to load a simple resource from my drawable. I created a bitmap which has a drawable as a source:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:src="@drawable/ball"/>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FF0000"/>
</shape>
I'm loading using this code:
bitmapDrawable = BitmapFactory.decodeResource( context.getResources(), R.drawable.bitmap_ball );
But they always return null. If bitmap xml exists and drawable too, what is the reason to this returns null?
Solution
The reason is in difference between Bitmaps and Drawables. Delete your "bitmap" file with
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:src="@drawable/ball"/>
content (leave in drawable folder only file with <shape xmlns:android... and give them name ball.xml) then add method
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
from this answer and call it like that:
Bitmap bitmapDrawable = drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.ball));
Answered By - Andrii Omelchenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.