Skip to content

Instantly share code, notes, and snippets.

@Gnzlt
Created November 2, 2016 14:25
Show Gist options
  • Save Gnzlt/6ddc846ef68c587d559f1e1fcd0900d3 to your computer and use it in GitHub Desktop.
Save Gnzlt/6ddc846ef68c587d559f1e1fcd0900d3 to your computer and use it in GitHub Desktop.
Android utils class to get a Bitmap from a VectorDrawable Resource Id (Took from http://qiita.com/konifar/items/aaff934edbf44e39b04a)
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.VectorDrawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.content.ContextCompat;
public class ResourceUtil {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Bitmap getBitmap(VectorDrawable vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
private static Bitmap getBitmap(VectorDrawableCompat vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
public static Bitmap getBitmap(Context context, @DrawableRes int drawableResId) {
Drawable drawable = ContextCompat.getDrawable(context, drawableResId);
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof VectorDrawableCompat) {
return getBitmap((VectorDrawableCompat) drawable);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("Unsupported drawable type");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment