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

前面在写 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了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值