本文介绍了自定义视图的双指缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了我的自定义视图,我想为我的自定义视图应用双指缩放.怎么做?
I have created my custom view and I want to apply pinch zoom for my custom view. How to do that?
推荐答案
Android 开发者博客上的这篇文章很好地涵盖了这个主题(向下滚动到 GestureDetectors 部分):
This article on the Android Developers Blog covers this topic very well (scroll down to the section on GestureDetectors):
如果您只想实现双指缩放,只需几行代码:
If you just want to implement pinch-to-zoom, there's only a few lines of code you'll need:
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public MyCustomView(Context mContext){
//...
//Your view code
//...
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
return true;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
//...
//Your onDraw() code
//...
canvas.restore();
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f));
invalidate();
return true;
}
}
本文的其余部分涉及处理其他手势,但不使用它们的实现,您可以使用 GestureDetector 就像上面代码中使用的 ScaleGestureDetector 一样.
The rest of the article deals with handling other gestures but rather than using their implementation, you can use GestureDetector just like ScaleGestureDetector is used in the code above.
这篇关于自定义视图的双指缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!