双指缩放的自定义视图 [英] Pinch zoom for custom view

查看:103
本文介绍了双指缩放的自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了我的自定义视图,我想申请双指缩放为我的自定义视图。那怎么办?

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.

这篇关于双指缩放的自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆