Android Image单指滑动双指缩放功能的最优写法
时间: 2023-08-27 17:03:51 浏览: 158
实现Android上的图片单指滑动和双指缩放功能,可以使用GestureDetector和ScaleGestureDetector两个类。具体步骤如下:
1. 在布局文件中添加一个ImageView,用于显示图片。
2. 在Activity中实例化GestureDetector和ScaleGestureDetector,并重写相应的回调方法。
```java
public class MainActivity extends AppCompatActivity implements
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener,
ScaleGestureDetector.OnScaleGestureListener {
private ImageView imageView;
private GestureDetector gestureDetector;
private ScaleGestureDetector scaleGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this);
scaleGestureDetector = new ScaleGestureDetector(this, this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
scaleGestureDetector.onTouchEvent(event);
return true;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// 单指滑动
if (e2.getPointerCount() == 1) {
float dx = e2.getX() - e1.getX();
float dy = e2.getY() - e1.getY();
imageView.scrollBy((int) dx, (int) dy);
return true;
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
// 双击缩放
float scale = imageView.getScaleX();
if (scale == 1.0f) {
imageView.setScaleX(2.0f);
imageView.setScaleY(2.0f);
} else {
imageView.setScaleX(1.0f);
imageView.setScaleY(1.0f);
}
return true;
}
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
// 双指缩放
float scaleFactor = detector.getScaleFactor();
float scale = imageView.getScaleX();
if (scaleFactor * scale >= 1.0f && scaleFactor * scale <= 3.0f) {
imageView.setScaleX(scaleFactor * scale);
imageView.setScaleY(scaleFactor * scale);
}
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
}
```
3. 在onTouchEvent方法中分别调用GestureDetector和ScaleGestureDetector的onTouchEvent方法。
4. 在重写的onScroll方法中,通过判断触摸点的数量来实现单指滑动。
5. 在重写的onDoubleTap方法中,通过判断当前的缩放比例来实现双击缩放。
6. 在重写的onScale方法中,通过ScaleGestureDetector获取缩放比例来实现双指缩放。
以上就是Android上实现图片单指滑动和双指缩放功能的最优写法。
阅读全文