How to create Bitmap form Drawable object

2019-04-13 12:56发布

问题:

I am developing custom view for android. For that I want give a user ability to select and image using just like when using ImageView

In attr.xml I added bellow code.

<declare-styleable name="DiagonalCut">
    <attr name="altitude" format="dimension"/>
    <attr name="background_image" format="reference"/>
</declare-styleable>

In custom view I get this value as a Drawable which was provided in xml as app:background_image="@drawable/image"

TypedArray typedArray = getContext().obtainStyledAttributes(arr, R.styleable.DiagonalCut);
altitude = typedArray.getDimensionPixelSize(R.styleable.DiagonalCut_altitude,10);
sourceImage = typedArray.getDrawable(R.styleable.DiagonalCut_background_image);

I want to create a Bitmap using this sourceImage which is a Drawable object.

If the way I'm going wrong please provide an alternative.

回答1:

You can convert your Drawable to Bitmap like this (for resource):

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.drawable_source);

OR

If you've it stored in a variable, you can use this :

public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        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;
}

More details