How to create Bitmap form Drawable object

余生长醉 提交于 2019-12-06 10:19:57

问题


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



来源:https://stackoverflow.com/questions/46531073/how-to-create-bitmap-form-drawable-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!