如何从Drawable对象创建位图

3

我正在为安卓开发自定义视图,为此我希望能够像使用ImageView一样让用户选择图片。

attr.xml中,我添加了以下代码:

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

在自定义视图中,我获取的值是一个Drawable,它在xml中作为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);

我希望能够使用这个Drawable对象sourceImage创建一个Bitmap。

如果我的方法有误,请提供替代方案。


Drawable出了什么问题?你为什么需要Bitmap?如果你真的需要Bitmap,那就使用BitmapFactory#decodeResource方法。 - pskink
1个回答

18
你可以像这样(对于资源)将 Drawable 转换为 Bitmap :
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.drawable_source);

或者

如果您已将其存储在变量中,可以使用以下代码:

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

更多详情


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接