将 SVG 图像解码为位图 [英] Decoding SVG image to bitmap

查看:31
本文介绍了将 SVG 图像解码为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Android Studio 将我的 SVG 图像转换为 XML 文件.当我尝试使用 R.drawable.svgimage 访问它时它工作正常,但现在我需要将该图像解码为位图.

I am using Android Studio to convert my SVG image to XML file . It works fine when I try to access it using R.drawable.svgimage but now I need to decode that image to bitmap.

我尝试了以下方法.它为位图返回 null.

I tried the following. It returns null for the bitmap.

mResId = R.drawable.svgimage
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeResource(
            mContext.getResources(), mResId, options); 

推荐答案

以下代码将完美运行我已经使用过它:这里 R.drawable.ic_airport 是我存储在 drawable 文件夹中的 svg 图像.

The following code will works perfectly I have used it: Here R.drawable.ic_airport is my svg image stored in drawable folder.

    @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);

这篇关于将 SVG 图像解码为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆