您的位置:首页 > 移动开发 > Android开发

Android应用开发——Drawable

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

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

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

引用图片资源

可以把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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: