问题描述
我正在为Android开发自定义视图.为此,我想赋予用户选择和成像的能力,就像使用ImageView
I am developing custom view for android. For that I want give a user ability to select and image using just like when using ImageView
在 attr.xml 中,我添加了以下代码.
In attr.xml I added bellow code.
<declare-styleable name="DiagonalCut">
<attr name="altitude" format="dimension"/>
<attr name="background_image" format="reference"/>
</declare-styleable>
在自定义视图中,我将此值作为Drawable
来获取,该值在xml中以app:background_image="@drawable/image"
In custom view I get this value as a Drawable
which was provided in xml as 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
(可绘制对象)创建位图.
I want to create a Bitmap using this sourceImage
which is a Drawable object.
如果我要走错路,请提供替代方法.
If the way I'm going wrong please provide an alternative.
推荐答案
您可以像这样(用于资源)将Drawable
转换为Bitmap
:
You can convert your Drawable
to Bitmap
like this (for resource):
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.drawable_source);
OR
如果您将其存储在变量中,则可以使用以下方法:
If you've it stored in a variable, you can use this :
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;
}
这篇关于如何创建位图表单Drawable对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!