SjN*_*erd 10 svg android bitmap
我正在使用Android Studio将我的SVG图像转换为XML文件.当我尝试使用R.drawable.svgimage访问它时它工作正常,但现在我需要将该图像解码为位图.
我尝试了以下内容.它为位图返回null.
mResId = R.drawable.svgimage
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
mContext.getResources(), mResId, options);
Run Code Online (Sandbox Code Playgroud)
小智 9
以下代码将完美地运行我使用它:这R.drawable.ic_airport是我的svg图像存储在drawable文件夹中.
@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);
Log.e(TAG, "getBitmap: 1");
return bitmap;
}
private static Bitmap getBitmap(Context context, int drawableId) {
Log.e(TAG, "getBitmap: 2");
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable) {
return BitmapFactory.decodeResource(context.getResources(), drawableId);
} else if (drawable instanceof VectorDrawable) {
return getBitmap((VectorDrawable) drawable);
} else {
throw new IllegalArgumentException("unsupported drawable type");
}
}
Bitmap bitmap = getBitmap(getContext(), R.drawable.ic_airport);
Run Code Online (Sandbox Code Playgroud)
In the package androidx.core.graphics.drawable there is a function Drawable.toBitmap
val yourBitmap = getDrawable(R.drawable.svgimage)!!.toBitmap(width, height)
Run Code Online (Sandbox Code Playgroud)