您的位置:首页 > Web前端

自定义属性reference 指向 Drawable 并转化为 Bitmap

2014-01-04 20:56 197 查看
前面在写  Android学习小demo(1)自定义View  的时候,自定义的drawable
属性是指向 drawable 中的某一张图片,如下:

attrs.xml

<resources>
<declare-styleable name="CustomRotateView">
<attr name="drawable" format="reference"/>
<attr name="degree" format="float" />
<attr name="bgcolor" format="color" />
</declare-styleable>
</resources>
Layout xml
<com.example.apidemostudy.CustomRotateView
android:id="@+id/rotateView1"
android:layout_width="240dip"
android:layout_height="300dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
custom:bgcolor="#000000"
custom:degree="0"
custom:drawable="@drawable/photo1" />


当时在自定义View 中获取这个属性的时候,是直接返回一个Drawable 属性,然后再将其转成一个Bitmap 的,代码如下:

Drawable drawable = typedArray.getDrawable(R.styleable.CustomRotateView_drawable);

private Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}


但其实有另外一种方法,在获取自定义的属性的的时候,可以利用typedArray 的 获取 资源ID (ResourceID) ,然后利用BitmapFactory 来创建Bitmap 的,代码如下:

int resId = typedArray.getResourceId(R.styleable.CustomRotateView_drawable, R.drawable.empty_photo);
mBitmap = BitmapFactory.decodeResource(getResources(), resId);


利用第二种方法,就不用自己再去写一个方法来将Drawable 转化成 Bitmap了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息