作者:明恋夏日2 | 来源:互联网 | 2023-01-15 18:37
我正在为android开发自定义视图.为此我想让用户能够选择和使用图像,就像使用时一样ImageView
在attr.xml中,我添加了以下代码.
在自定义视图中,我得到的值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> Ashish Ranja..:
您可以将您转换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;
}
更多细节