转载自: https://blog.csdn.net/u010246789/article/details/51461566
clip使用
定义:通过图片的level来控制剪切,使用剪切图像资源可以只显示一部分图像,这种资源经常被用在进度条的制作上。剪切图像资源是一个XML格式文件,资源只包含一个标签。
使用:
<?xml version="1.0" encoding="utf-8"?>
<clip
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/drawable_resource"
android:clipOrientation=["horizontal" | "vertical"]
android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
"fill_vertical" | "center_horizontal" | "fill_horizontal" |
"center" | "fill" | "clip_vertical" | "clip_horizontal"] />
官方示例:
XML file saved at res/drawable/clip.xml:
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/android"
android:clipOrientation="horizontal"
android:gravity="left" />
The following layout XML applies the clip drawable to a View:
<ImageView
android:id="@+id/image"
android:background="@drawable/clip"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
The following code gets the drawable and increases the amount of clipping in order to progressively reveal the image:
ImageView imageview = (ImageView) findViewById(R.id.image);
ClipDrawable drawable = (ClipDrawable) imageview.getDrawable();
drawable.setLevel(drawable.getLevel() + 1000);
注意:1、imageview.getDrawable()实际使用时会报空指针,可以使用getBackground()代替。
2、ClipDrawable类内部预设了一个最大的level值10000(Android SDK未提供API修改该值)。如果这个level的值为0,表示截取图像的宽度或高度为0,也就是说,图像就无法显示了。如果level的值为10000,表示显示全部的图像(不进行任何截取)。
效果:
1、xml中:
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="horizontal"
android:drawable="@mipmap/reasource_drawable_mn3"
android:gravity="right">
</clip>
2、Layout中:
<ImageView
android:id="@+id/img_clip"
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="@drawable/resource_drawable_clip"/>
<Button
android:id="@+id/btn_clip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始裁剪"/>
3、Activity中:
img_clip = (ImageView) findViewById(R.id.img_clip);
ClipDrawable drawable_clip = (ClipDrawable) img_clip.getBackground();
drawable_clip.setLevel(drawable_clip.getLevel() + 3000);
PS: 本例将level设为3000,表示从右侧截取30%的图像。
扩展小例子:
1、在上面的基础上将android:gravity="right"改为android:gravity=“center”。
2、增加按钮点击事件,将
ClipDrawable drawable_clip = (ClipDrawable) img_clip.getBackground();
drawable_clip.setLevel(drawable_clip.getLevel() + 3000);
改为:
btn_clip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ClipDrawable drawable_clip = (ClipDrawable) img_clip.getBackground();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
int level = drawable_clip.getLevel();
if(level < 10000){
drawable_clip.setLevel(drawable_clip.getLevel() + 100);
new Handler().postDelayed(this, 100);
}
}
}, 1000);
}
});