我正在为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对象。
如果我出错的方式请提供替代方案。
答案 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;
}