Search code examples
androidbitmapandroid-drawablenine-patch

NinePatchDrawable cannot be cast to android.graphics.drawable.BitmapDrawable


I use a nine patch drawable in imageview and using below code I want to get Bitmap but this error happens.

 Bitmap stickerBitmap = ((BitmapDrawable) Front.getDrawable()).getBitmap();

Solution

  • You cannot directly cast a NinePatchDrawable to a BitmapDrawable, since those are two different incompatible drawable types.

    If you want to get a Bitmap from a non-BitmapDrawable you have to draw it with a Canvas onto a Bitmap:

    Drawable drawable = Front.getDrawable();
    Bitmap stickerBitmap = Bitmap.createBitmap(Front.getWidth(),
            Front.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(stickerBitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    

    Note that your ImageView has to be layouted so that it has a non-zero size.