无法将矢量drawable转换为android中的位图drawable

时间:2016-11-04 07:35:52

标签: android vector bitmap

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

 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)

2 个答案:

答案 0 :(得分:0)

您无法将VectorDrawable强制转换为BitmapDrawable。他们没有亲子关系。它们都是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;
}

答案 1 :(得分:0)

你可以试试这个。它对我很好。

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