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);




更多相关文章

  1. Android图片加载后变小
  2. Android实现图片轮播切换实例代码
  3. LeakCanary的使用
  4. Android(安卓)设计模式之Builder模式
  5. Android(安卓)通过API获取数据库中的图片文件方式
  6. Android中创建倒影效果的工具类
  7. Android应用程序(APK)的构建过程
  8. Android图集的上下左右拖动及动画效果研究,图片拖拽或视频拖拽
  9. android 加载大图片防止内存溢出

随机推荐

  1. 如何实现android清理后台时,自己的软件不
  2. Android之Action Bar
  3. android layout属性
  4. Android(安卓)之 Retrofit 入门介绍
  5. Smalidea+IntelliJ IDEA/Android(安卓)St
  6. Android设置一个按钮右对齐
  7. Google Android(安卓)for Cars的整理Andr
  8. android:layout_weight属性详解
  9. Mysql动态更新数据库脚本的示例讲解
  10. CentOS7编译安装MySQL5.7.24的教程详解