Android应用开发——Drawable

Android提供了一个自定义的2D图形库,它可以绘制形状和图片。在android.graphics.drawable包中可以找到普通类来绘制2D图形。Drawable子类中包含了许多特定类型的图形,像BitmapDrawable,ShapeDrawable,PictureDrawable,LayerDrawable等等。当然,也可以通过继承这些类来实现自己的Drawable对象。


有三种定义和实例化Drawable的方法:

  1. 引用图片资源方式。(res/drawable)
  2. 使用图片资源的XML方式。
  3. 使用普通的类构造器方法。

引用图片资源

可以把PNG (preferred), JPG (acceptable) and GIF (discouraged)的图片格式放在项目的res/drawable目录中,然后在项目中引用这些资源。

Notice:放在res/drawable目录下的文件都会自动地经过aapt工具压缩优化,如果想要得到图片文件完整的二进制数据,可以把图片文件放在res/raw目录下。

假设在res/drawable中有一张my_image.png的图片,那么

在ImageView中使用图片资源:

// Instantiate an ImageView and define its properties
  ImageView i = new ImageView(this);
  i.setImageResource(R.drawable.my_image);
  i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions
  i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
  LayoutParams.WRAP_CONTENT));

获取该图片的Drawable对象:

Resources res = mContext.getResources();
    Drawable myImage = res.getDrawable(R.drawable.my_image);

在XML文件中引用图片资源:

<ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:tint="#55ff0000"
      android:src="@drawable/my_image"/>

使用图片资源的XML方式

当你需要你的图片资源在使用的时候能改变它的属性,那么就应该使用XML方式: res/drawable/expand_collapse.xml
 <transition xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:drawable="@drawable/image_expand">
      <item android:drawable="@drawable/image_collapse">
 </transition>

通过硬代码实例化资源:
Resources res = mContext.getResources();
      TransitionDrawable transition = (TransitionDrawable)
res.getDrawable(R.drawable.expand_collapse);
      ImageView image = (ImageView) findViewById(R.id.toggle_image);
      image.setImageDrawable(transition);

这个transitionDrawable可以在1秒后转变:
transition.startTransition(1000);




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值