android 从矢量图SVG获取位图bitmap

关键代码

public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId) {
    Drawable drawable = ContextCompat.getDrawable(context, drawableId);

    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof VectorDrawable || drawable instanceof VectorDrawableCompat) {
        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;
    } else {
        throw new IllegalArgumentException("unsupported drawable type");
    }
}

需要配置以下代码

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

原文连接
http://stackoverflow.com/questions/33696488/getting-bitmap-from-vector-drawable

你可能感兴趣的:(Android)