将 SVG 图像解码为位图

新手上路,请多包涵

我正在使用 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);

原文由 Siju 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 735
2 个回答

在包中 androidx.core.graphics.drawable 有一个函数 Drawable.toBitmap

 val yourBitmap = getDrawable(R.drawable.svgimage)!!.toBitmap(width, height)

原文由 Benjamin Basmaci 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 Harsh Mittal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题