如何创建可绘制对象的位图

时间:2017-10-02 17:59:59

标签: android bitmap android-canvas android-custom-view

我正在为android开发自定义视图。为此,我希望为用户提供选择和图像使用的能力,就像使用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);

我想使用这个sourceImage创建一个Bitmap,它是一个Drawable对象。

如果我出错的方式请提供替代方案。

1 个答案:

答案 0 :(得分:10)

您可以将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;
}

More details