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

Cha*_*hna 2 android bitmap android-custom-view android-canvas

我正在为android开发自定义视图.为此我想让用户能够选择和使用图像,就像使用时一样ImageView

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

<declare-styleable name="DiagonalCut">
    <attr name="altitude" format="dimension"/>
    <attr name="background_image" format="reference"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

在自定义视图中,我得到的值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);
Run Code Online (Sandbox Code Playgroud)

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

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

Ash*_*jan 12

您可以将您转换DrawableBitmap这样(对于资源):

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.drawable_source);
Run Code Online (Sandbox Code Playgroud)

要么

如果它存储在变量中,您可以使用:

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;
}
Run Code Online (Sandbox Code Playgroud)

更多细节