官方文档:
A Drawable that clips another Drawable based on this Drawable's current level value. You can control how much the child Drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars, by increasing the drawable's level with setLevel().
Note: The drawable is clipped completely and not visible when the level is 0 and fully revealed when the level is 10,000.
It can be defined in an XML file with the <clip> element. For more information, see the guide to Drawable Resources.
简单地讲:ClipDrawable对象是一个Drawable对象,用来剪切原有的Drawabe对象(根据level值剪切),形成“片段”。level范围(0-10000),0为不可见,10000为全显示。
如果在XML文件中定义ClipDrawable对象的话,需要使用<clip>元素。截取的方向由clipOrientation属性控制。
贴出例子:
ClipDrawable资源文件:clip_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- clipOrientation属性设置图片截取的方向 -->
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/jellybean"
android:clipOrientation="horizontal"
android:gravity="center">
</clip>
布局文件中:main.xml (ImageView控件中设置ClipDrawable资源文件)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/clip_drawable" />
</LinearLayout>
主Activity代码:ClipDrawableTest.java
package com.cb.clipdrawable;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.crazyit.image.R;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class ClipDrawableTest extends Activity {
ImageView mImageView;
Drawable mDrawable;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.image);
mDrawable = mImageView.getDrawable();
//使用一个timer对象控制发送消息
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Message msg = new Message();
mHandler.sendMessage(msg);
//level 取值范围0-10000.
if (mDrawable.getLevel() >= 10000) {
timer.cancel();
}
}
}, 0, 200);
/*
try {
//设置壁纸
setWallpaper(BitmapFactory.decodeResource(getResources(), R.drawable.jellybean));
} catch (IOException e) {
e.printStackTrace();
}
*/
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
//设置图片:每次根据level值的变化而变化,再显示出来
mDrawable.setLevel(mDrawable.getLevel() + 200);
}
};
}
渐变前图片:
渐变后图片:
本文介绍了Android中ClipDrawable的应用,这是一种可以根据level值剪切原始Drawable对象的工具。文章通过实例展示了如何使用XML定义ClipDrawable,并通过代码实现渐变效果。
189

被折叠的 条评论
为什么被折叠?



