Android触摸放大缩小
时间: 2023-10-25 11:14:48 浏览: 99
Android的触摸放大缩小功能可以通过实现GestureDetector类来实现。以下是一个简单的示例代码:
```java
public class MyView extends View {
private Paint paint;
private Bitmap bitmap;
private float scaleFactor = 1.0f;
private GestureDetector gestureDetector;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
gestureDetector = new GestureDetector(getContext(), new MyGestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.restore();
}
private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(0.1f, Math.min(scaleFactor, 5.0f));
invalidate();
return true;
}
}
}
```
在这个示例中,我们使用了GestureDetector和ScaleGestureDetector来实现放大缩小功能。我们在MyView类中重写了onTouchEvent()方法来接收触摸事件,然后将事件传递给gestureDetector处理。在MyGestureListener类中,我们重写了onScale()方法,该方法在用户进行放大缩小手势时被调用,我们在此方法中更新scaleFactor变量,然后调用invalidate()方法强制视图重新绘制。最后,在onDraw()方法中,我们调用canvas.scale()方法来缩放画布,然后绘制位图。
阅读全文