用簡單的方法,在android上實現手勢放大縮小功能

來源:互聯網
上載者:User

用簡單的方法,在android上實現手勢放大縮小功能

package com.example.eventtest;import java.util.ArrayList;import android.os.Bundle;import android.app.Activity;import android.gesture.GestureOverlayView;import android.gesture.GestureOverlayView.OnGestureListener;import android.graphics.Point;import android.view.Menu;import android.view.MotionEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.Toast;public class MainActivity extends Activity {double nLenStart = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onTouchEvent(MotionEvent event) {int nCnt = event.getPointerCount();int n = event.getAction();if( (event.getAction()&MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN && 2 == nCnt)//2表示兩個手指{for(int i=0; i< nCnt; i++){float x = event.getX(i);float y = event.getY(i);Point pt = new Point((int)x, (int)y);}int xlen = Math.abs((int)event.getX(0) - (int)event.getX(1));int ylen = Math.abs((int)event.getY(0) - (int)event.getY(1));nLenStart = Math.sqrt((double)xlen*xlen + (double)ylen * ylen);}else if( (event.getAction()&MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_UP  && 2 == nCnt){for(int i=0; i< nCnt; i++){float x = event.getX(i);float y = event.getY(i);Point pt = new Point((int)x, (int)y);}int xlen = Math.abs((int)event.getX(0) - (int)event.getX(1));int ylen = Math.abs((int)event.getY(0) - (int)event.getY(1));double nLenEnd = Math.sqrt((double)xlen*xlen + (double)ylen * ylen);if(nLenEnd > nLenStart)//通過兩個手指開始距離和結束距離,來判斷放大縮小{Toast.makeText(getApplicationContext(), "放大", 3000).show();}else{Toast.makeText(getApplicationContext(), "縮小", 3000).show();}}return super.onTouchEvent(event);}}


基礎知識:

getAction()方法返回的是int類型,用到的只有低16位,其中:低八位是動作的類型,高8位是觸摸點索引值的表示(單點為0,雙點為1)

獲得動作類型: int action = event.getAction() &ACTION_MASK 或者使用 getActionMasked()

獲得觸摸點索引類型: int pointerIndex = (event.getAction() &ACTION_POINTER_INDEX_MASK ) >> ACTION_POINTER_INDEX_SHIFT

或者使用 getActionIndex()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.