自定义属性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>
当时在自定义View 中获取这个属性的时候,是直接返回一个Drawable 属性,然后再将其转成一个Bitmap 的,代码如下:
但其实有另外一种方法,在获取自定义的属性的的时候,可以利用typedArray 的 获取 资源ID (ResourceID) ,然后利用BitmapFactory 来创建Bitmap 的,代码如下:
利用第二种方法,就不用自己再去写一个方法来将Drawable 转化成 Bitmap了。
属性是指向 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了。
相关文章推荐
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable,InputStream相互转化
- Android中Bitmap,byte[],Drawable相互转化
- android----Bitmap / Drawable / byte[] 之间相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- android_drawable类型转化为bitmap
- (转)Android自定义属性时format选项( <attr format="reference" name="background" /> )
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable,InputStream相互转化工具类
- Android Bitmap与byte[]、Bitmap与Drawable相互转化
- Android学习之路------自定义drawable之shape属性
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap,byte[],Drawable相互转化
- Android中Bitmap, Drawable, Byte之间的转化
- Android中Bitmap,byte[],Drawable相互转化