如何防止Android矢量每次都被重新放大和重绘为位图?

如何防止Android矢量每次都被重新放大和重绘为位图?,android,android-vectordrawable,Android,Android Vectordrawable,我正在读这篇关于矢量绘图的文章。有人提到,使用矢量图像的一个权衡是渲染成本更高。该博客还指出: 对于静态向量,绘图阶段只需执行一次,然后就可以缓存到位图中 但是博客没有解释如何进行缓存。怎么做?以下是一些方法: public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) { Drawable drawable = ContextCompat.getDrawable(context, d

我正在读这篇关于矢量绘图的文章。有人提到,使用矢量图像的一个权衡是渲染成本更高。该博客还指出:

对于静态向量,绘图阶段只需执行一次,然后就可以缓存到位图中


但是博客没有解释如何进行缓存。怎么做?

以下是一些方法:

public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);
// depending on the support lib version you may have to use
//  Drawable drawable = AppCompatResources.getDrawable(context, drawableId);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        drawable = (DrawableCompat.wrap(drawable)).mutate();
    }

    Bitmap 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;
}
希望能有帮助

val bitmap = AppCompatResources.getDrawable(context, drawableId).toBitmap()