首页 > 代码库 > 多点触摸的操作与图片放大缩小
多点触摸的操作与图片放大缩小
1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.view.MotionEvent; 4 import android.view.View; 5 import android.widget.FrameLayout; 6 import android.widget.FrameLayout.LayoutParams; 7 import android.widget.ImageView; 8 9 public class MainActivity extends Activity {10 11 private ImageView iv;12 private FrameLayout root;13 14 @Override15 protected void onCreate(Bundle savedInstanceState) {16 super.onCreate(savedInstanceState);17 setContentView(R.layout.activity_main);18 19 root = (FrameLayout) findViewById(R.id.container);20 iv = (ImageView) findViewById(R.id.iv);21 22 root.setOnTouchListener(new View.OnTouchListener() {23 24 float currentDistance;25 float lastDistance = -1; // 记录最有一次所记录的值26 27 @Override28 public boolean onTouch(View v, MotionEvent event) {29 30 switch (event.getAction()) {31 case MotionEvent.ACTION_DOWN: // 触摸按下32 System.out.println("action down");33 break;34 case MotionEvent.ACTION_MOVE: // 触摸移动35 // System.out.println("action move");36 System.out.println("触摸点个数:" + event.getPointerCount());37 38 if (event.getPointerCount() >= 2) { // 判断大于等于两个触摸点39 40 float offsetX = event.getX(0) - event.getX(1);41 float offsetY = event.getY(0) - event.getY(1);42 // 计算出两个点之间的距离43 currentDistance = (float) Math.sqrt(offsetX * offsetX44 + offsetY * offsetY);45 46 if (lastDistance < 0) { // 初始值47 lastDistance = currentDistance;48 } else {49 // 当前距离比上次距离>5个像素,可以识别为放大。50 if (currentDistance - lastDistance > 5) { 51 System.out.println("放大");52 53 FrameLayout.LayoutParams lp = (LayoutParams) iv54 .getLayoutParams();55 lp.width = (int) (1.1f * iv.getWidth());56 lp.height = (int) (1.1f * iv.getHeight());57 58 iv.setLayoutParams(lp);59 60 lastDistance = currentDistance;61 } else if (lastDistance - currentDistance > 5) { //62 System.out.println("缩小");63 64 FrameLayout.LayoutParams lp = (LayoutParams) iv65 .getLayoutParams();66 lp.width = (int) (0.9f * iv.getWidth());67 lp.height = (int) (0.9f * iv.getHeight());68 69 iv.setLayoutParams(lp);70 71 lastDistance = currentDistance;72 }73 }74 }75 break;76 case MotionEvent.ACTION_UP: // 触摸弹起77 // System.out.println("action up");78 break;79 }80 81 return true;82 }83 });84 }85 86 }
1 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/container" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 tools:context="com.jikexueyuan.multouch.MainActivity" 7 tools:ignore="MergeRootFrame" > 8 9 <ImageView10 android:id="@+id/iv"11 android:layout_width="wrap_content"12 android:layout_height="wrap_content"13 android:src="@drawable/ic_launcher" />14 15 </FrameLayout>
多点触摸的操作与图片放大缩小
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。