我已经创建了我的自定义视图,我想申请双指缩放为我的自定义视图。那怎么办?
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):
制作多点触摸感
如果你只是想实现双指缩放,有$ C $只有几行C,你需要:
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用在code以上。
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.
更多推荐
双指缩放的自定义视图
发布评论