Android中圖片的裁剪和徐徐展開控制元件ClipDrawable
阿新 • • 發佈:2019-02-11
ClipDrawable代表從其他點陣圖上擷取一個“圖片片段”,在XML檔案中用<clip.../>元素定義ClipDrawable物件,可可指定如下三個屬性:
android:drawable:指定擷取的源Drawable物件
android:clipOrientation:指定擷取的方向,可設定為水平擷取或垂直擷取
android:gravity:指定擷取時的對齊方式
使用ClipDrawable物件時可以呼叫setLevel(int level)方法來設定擷取的區域大小(最大為10000),當level為0時,擷取的圖片片段為空;當level為10000時,擷取整張圖片。
通過以上說明,我們發現,可以使用ClipDrawable的這種性質控制擷取圖片的區域大小,讓程式不斷呼叫setLevel方法並改變level的值,達到讓圖片慢慢展開的效果 。
下面是一個demo例子,showDrawable()和clip()兩種方法分別表示圖片徐徐展開和裁剪:
1.drawable中的clip:
<?xml version="1.0" encoding="utf-8"?> <clip xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/mg4" android:clipOrientation="horizontal" android:gravity="center"> </clip>2.主函式的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.wls.clipdrawabledemo.MainActivity"3.主函式Mainactivity:> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="開始展示圖片" android:onClick="btnClick"/> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="裁剪圖片" android:onClick="btnClick"/> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/drawable_clip"/> </LinearLayout>
public class MainActivity extends AppCompatActivity { private ImageView mImageView; private ClipDrawable mDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { mImageView = (ImageView) findViewById(R.id.image); mDrawable = (ClipDrawable) mImageView.getDrawable(); } public void btnClick(View view){ switch (view.getId()){ case R.id.button1: showDrawable(); break; case R.id.button2: clip(); break; } } /** * 圖片的展開 * 其中 mDrawable.setLevel(mDrawable.getLevel() + 200)和timer中的時間相互配合 * 可以控制圖片的展開速度和時間 * */ private void showDrawable(){ final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what == 1){ mDrawable.setLevel(mDrawable.getLevel() + 200); } } }; final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); if(mDrawable.getLevel() >= 10000){ timer.cancel(); } } },0,100); } /** * 圖片的裁剪 */ private void clip(){ mDrawable.setLevel(5000); } }4.效果展示:
裁剪的效果: