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

android学习笔记之使用ClipDrawable

2013-06-01 14:17 393 查看
ClipDrawable代表从其它位图上截取一个“图片片段”。在XML文件中使用<clip.../>元素定义ClipDrawable对象,可指定如下三个属性:

android:drawable:指定截取的源Drawable对象
android:clipOrientation:指定截取的方向,可设置为水平截取或垂直截取
android:gravity:指定截取时的对齐方式

使用ClipDrawable对象时可以调用setLevel(int level)方法来设置截取的区域大小,当level为0时,截取的图片片段为空;当level为10000时,截取整张图片。

通过以上说明,我们发现,可以使用ClipDrawable的这种性质控制截取图片的区域大小,让程序不断调用setLevel方法并改变level的值,达到让图片慢慢展开的效果。



首先,我们定义一个ClipDrawable对象:

<?xml version="1.0" encoding="UTF-8"?>
<clip
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/muller"
    android:clipOrientation="horizontal"
    android:gravity="center" >
    
</clip>



接下来,简单设置下布局文件,使得图片能够显示在屏幕上(注意ImageView的src属性的选择):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/clip" />

</LinearLayout>



下面在主程序中设置一个定时器来改变level值:

public class MainActivity extends Activity
{
    private ImageView view=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.view=(ImageView)super.findViewById(R.id.view);
		//获取图片所显示的ClipDrawable对象
		final ClipDrawable drawable=(ClipDrawable) view.getDrawable();
		final Handler handler=new Handler()
		{
			@Override
			public void handleMessage(Message msg) 
			{
				//如果消息是本程序发送的
				if(msg.what==0x123)
				{
					//修改ClipDrawable的level值
					drawable.setLevel(drawable.getLevel()+200);
				}
			}		
		};
		final Timer timer=new Timer();
		timer.schedule(new TimerTask()
		{
			@Override
			public void run() 
			{
				Message msg=new Message();
				msg.what=0x123;
				//发送消息,通知应用修改ClipDrawable的level的值
				handler.sendMessage(msg);
				//取消定时器
				if(drawable.getLevel()>=10000)
				{
					timer.cancel();
				}
			}
		}, 0,300);
	}

}


程序运行效果截图:





实际上,在实际应用中我们完全可以用这种ClipDrawable对象来实现图片进度条,感兴趣的同学可以自己试着写一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: