【问题标题】:Unable to convert vector drawable to bitmap drawable in android无法在android中将矢量可绘制转换为位图可绘制
【发布时间】:2016-11-04 07:35:51
【问题描述】:

我正在尝试将位图转换为字节数组,其中我将矢量可绘制图像转换为位图,然后我将其转换为字节数组,但是当我打开应用程序时它显示错误类转换异常无法转换矢量可绘制到位图可绘制。

 Resources res = getResources();
   Drawable drawable = res.getDrawable(R.drawable.ic_motorcycle_black);
    if (drawable != null) {
        drawable.setColorFilter(0xffff0000, PorterDuff.Mode.MULTIPLY);
    }
    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    final byte[] bike = stream.toByteArray();

错误:

  Caused by: java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
                                                                  at codingtown.coconut.otherexpense.activity.AddNewExpenseCategoryActivity.intialize(AddNewExpenseCategoryActivity.java:82)
                                                                  at codingtown.coconut.otherexpense.activity.AddNewExpenseCategoryActivity.onCreate(AddNewExpenseCategoryActivity.java:67)
                                                                  at android.app.Activity.performCreate(Activity.java:6092)
                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)

【问题讨论】:

标签: android vector bitmap


【解决方案1】:

你可以试试这个。对我来说效果很好。

private BitmapDescriptor bitmapDescriptorFromVector(Context context, @DrawableRes  int vectorDrawableResourceId) {
    Drawable background = ContextCompat.getDrawable(context, R.drawable.ic_map_pin_filled_blue_48dp);
    background.setBounds(0, 0, background.getIntrinsicWidth(), background.getIntrinsicHeight());
    Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
    vectorDrawable.setBounds(40, 20, vectorDrawable.getIntrinsicWidth() + 40, vectorDrawable.getIntrinsicHeight() + 20);
    Bitmap bitmap = Bitmap.createBitmap(background.getIntrinsicWidth(), background.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    background.draw(canvas);
    vectorDrawable.draw(canvas);
    return BitmapDescriptorFactory.fromBitmap(bitmap);
}

【讨论】:

    【解决方案2】:

    您不能将 VectorDrawable 转换为 BitmapDrawable。他们没有亲子关系。它们都是 Drawable 类的直接子类。

    要从 drawable 中获取位图,您需要从 drawable 元数据中创建位图。

    可能是 like this 在单独的方法中,

    try {
        Bitmap bitmap;
    
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
    
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    } catch (OutOfMemoryError e) {
        // Handle the error
        return null;
    }
    

    【讨论】: