標籤:android 多點觸控 圖片縮放
本文主要介紹Android的多點觸控,使用了一個圖片縮放的執行個體,來更好的說明其原理。需要實現OnTouchListener介面,重寫其中的onTouch方法。
實現:
原始碼:
布局檔案:
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /></RelativeLayout>
代碼:
package com.multitouch;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.RelativeLayout.LayoutParams;/** * 多點觸控Demo執行個體: 圖片的縮放。 * */public class MainActivity extends Activity {private RelativeLayout layout;protected String TAG = "zhongyao";private ImageView imageView;private float currentDistance;private float lastDistance = -1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);layout = (RelativeLayout) findViewById(R.id.layout);imageView = (ImageView) findViewById(R.id.imageView);layout.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {/** * 手指按下 */case MotionEvent.ACTION_DOWN:Log.d(TAG, "down!!!");break;/** * 手指移動 */case MotionEvent.ACTION_MOVE:Log.d(TAG, "move!!!");/** * 首先判斷按下手指的個數是不是大於兩個。 * 如果大於兩個則執行以下操作(即圖片的縮放操作)。 */if (event.getPointerCount() >= 2) {float offsetX = event.getX(0) - event.getX(1);float offsetY = event.getY(0) - event.getY(1);/** * 原點和滑動後點的距離差 */currentDistance = (float) Math.sqrt(offsetX * offsetX+ offsetY * offsetY);if (lastDistance < 0) {lastDistance = currentDistance;} else {/** * 如果當前滑動的距離(currentDistance)比最後一次記錄的距離(lastDistance)相比大於5英寸(也可以為其他尺寸), * 那麼現實圖片放大 */if (currentDistance - lastDistance > 5) {Log.d(TAG, "放大!!!");RelativeLayout.LayoutParams lp = (LayoutParams) imageView.getLayoutParams();/** * 圖片寬高一次放大為原來圖片的1.1倍(當然,也可以為其他數值)。 */lp.width = (int) (imageView.getWidth() * 1.1);lp.height = (int) (imageView.getHeight() * 1.1);imageView.setLayoutParams(lp);lastDistance = currentDistance;/** * 如果最後的一次記錄的距離(lastDistance)與當前的滑動距離(currentDistance)相比小於5英寸, * 那麼圖片縮小。 */} else if (lastDistance - currentDistance > 5) {Log.d(TAG, "縮小!!!");RelativeLayout.LayoutParams lp = (LayoutParams) imageView.getLayoutParams();/** * 圖片寬高一次縮小為原來圖片的0.9倍。 */lp.width = (int) (imageView.getWidth() * 0.9);lp.height = (int) (imageView.getHeight() * 0.9);imageView.setLayoutParams(lp);lastDistance = currentDistance;}}}break;/** * 手指抬起 */case MotionEvent.ACTION_UP:Log.d(TAG, "up!!!");break;}return true;}});}}
原始碼下載:
點擊下載源碼