文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android手势ImageView三部曲 第三部

2022-06-06 11:23

关注

接着上一节 Android手势ImageView三部曲(二)的往下走,我们讲到了github上的GestureDetector框架,
先附上github链接:
https://github.com/Almeros/android-gesture-detectors
其实把这个框架的主体思想也是参考的Android自带的ScaleGestureDetector工具类,ScaleGestureDetector估计是参考的GestureDetector工具类,不管谁参考谁的,既然被我们遇到了,我们就要变成自己的东西,真不能全变成自己的东西的话,至少

我们要了解下它的思想。

我们先了解一下android自带的ScaleGestureDetector(缩放手势监测器):

ScaleGestureDetector跟GestureDetector构造都差不多,但是ScaleGestureDetector只能用于监测缩放的手势,而GestureDetector监测的手势就比较多了,我们上一节内容中有提到。

ScaleGestureDetector的一些用法跟api,小伙伴自行去查看官网文档:
https://developer.android.google.cn/reference/android/view/ScaleGestureDetector.html

我们怎么使用它呢(我以第一节中最后一个demo为例)?

首先创建一个ScaleGestureDetector对象:


 private void initView() {
    ....
    mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleListener());
    ....
  }

然后传递一个叫ScaleListener的回调接口给它,ScaleListener里面有三个回调方法:


 private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
      mScaleFactor *= detector.getScaleFactor(); // scale change since previous event
      // Don't let the object get too small or too large.
      mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
      changeMatrix();
      return true;
    }
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
      return super.onScaleBegin(detector);
    }
    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
      super.onScaleEnd(detector);
    }
  }

小伙伴应该看得懂哈,就是onScale放缩时回调,onScaleBegin缩放开始时回调,onScaleEnd缩放完毕后回调。

最后在view的onTouchEvent方法中把事件给ScaleGestureDetector对象:


@Override
  public boolean onTouchEvent(MotionEvent event) {
    //把缩放事件给mScaleDetector
    mScaleDetector.onTouchEvent(event);
    return true;
  }
好啦~!!上

一节最后的时候,我写了一个小demo去实现了图片的位移,下面我们继续加上图片的缩放:


public class MatrixImageView extends ImageView {
  private Matrix currMatrix;
  private GestureDetector detector;
  private ScaleGestureDetector scaleDetector;
  private float currX;//当前图片的x坐标值
  private float currY;//当前图片的y坐标值
  private float scaleFactor=1f;//当前图片的缩放值
  public MatrixImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initView();
    detector=new GestureDetector(context,onGestureListener);
    //创建一个缩放手势监测器
    scaleDetector=new ScaleGestureDetector(context,onScaleGestureListener);
  }
  private void initView() {
    currMatrix = new Matrix();
    DisplayMetrics dm = getResources().getDisplayMetrics();
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
    bitmap = Bitmap.createScaledBitmap(bitmap, dm.widthPixels, dm.heightPixels, true);
    setImageBitmap(bitmap);
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    detector.onTouchEvent(event);
    //把事件给scaleDetector
    scaleDetector.onTouchEvent(event);
    return true;
  }
  private void setMatrix(){
    currMatrix.reset();
    currMatrix.postTranslate(currX,currY);
    currMatrix.postScale(scaleFactor,scaleFactor,getMeasuredWidth()/2,getMeasuredHeight()/2);
    setImageMatrix(currMatrix);
  }
  private GestureDetector.SimpleOnGestureListener onGestureListener=new GestureDetector.SimpleOnGestureListener(){
    @Override
    public boolean onDown(MotionEvent e) {
      return true;
    }
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
      currX-=distanceX;
      currY-=distanceY;
      setMatrix();
      return super.onScroll(e1, e2, distanceX, distanceY);
    }
  };
  private ScaleGestureDetector.SimpleOnScaleGestureListener onScaleGestureListener=new ScaleGestureDetector.SimpleOnScaleGestureListener(){
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
      scaleFactor*=detector.getScaleFactor();
      setMatrix();
      
      return true;
    }
  };
}

尴尬了,模拟器不太好用于两个手指缩放的录制,所以效果小伙伴自己拿到代码运行一下哈~!!!

下面一起撸一撸ScaleGestureDetector的源码:
我们知道,ScaleGestureDetector核心代码也就是onTouchEvent,于是我们点开onTouchEvent:


@SuppressLint("NewApi")
  public boolean onTouchEvent(MotionEvent event) {
    //获取当前event事件
    mCurrTime = event.getEventTime();
    final int action = event.getActionMasked();
    // Forward the event to check for double tap gesture
    if (mQuickScaleEnabled) {
      mGestureDetector.onTouchEvent(event);
    }
    //获取手指个数
    final int count = event.getPointerCount();
    final boolean isStylusButtonDown =
        (event.getButtonState() & MotionEvent.BUTTON_STYLUS_PRIMARY) != 0;
    final boolean anchoredScaleCancelled =
        mAnchoredScaleMode == ANCHORED_SCALE_MODE_STYLUS && !isStylusButtonDown;
    final boolean streamComplete = action == MotionEvent.ACTION_UP ||
        action == MotionEvent.ACTION_CANCEL || anchoredScaleCancelled;
    //手指按下的时候
    if (action == MotionEvent.ACTION_DOWN || streamComplete) {
      // Reset any scale in progress with the listener.
      // If it's an ACTION_DOWN we're beginning a new event stream.
      // This means the app probably didn't give us all the events. Shame on it.
      if (mInProgress) {
        mListener.onScaleEnd(this);
        mInProgress = false;
        mInitialSpan = 0;
        mAnchoredScaleMode = ANCHORED_SCALE_MODE_NONE;
      } else if (inAnchoredScaleMode() && streamComplete) {
        mInProgress = false;
        mInitialSpan = 0;
        mAnchoredScaleMode = ANCHORED_SCALE_MODE_NONE;
      }
      if (streamComplete) {
        return true;
      }
    }
    if (!mInProgress && mStylusScaleEnabled && !inAnchoredScaleMode()
        && !streamComplete && isStylusButtonDown) {
      // Start of a button scale gesture
      mAnchoredScaleStartX = event.getX();
      mAnchoredScaleStartY = event.getY();
      mAnchoredScaleMode = ANCHORED_SCALE_MODE_STYLUS;
      mInitialSpan = 0;
    }
    final boolean configChanged = action == MotionEvent.ACTION_DOWN ||
        action == MotionEvent.ACTION_POINTER_UP ||
        action == MotionEvent.ACTION_POINTER_DOWN || anchoredScaleCancelled;
    final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP;
    final int skipIndex = pointerUp ? event.getActionIndex() : -1;
    //处理多点之间距离
    float sumX = 0, sumY = 0;
    final int div = pointerUp ? count - 1 : count;
    final float focusX;
    final float focusY;
    if (inAnchoredScaleMode()) {
      // In anchored scale mode, the focal pt is always where the double tap
      // or button down gesture started
      focusX = mAnchoredScaleStartX;
      focusY = mAnchoredScaleStartY;
      if (event.getY() < focusY) {
        mEventBeforeOrAboveStartingGestureEvent = true;
      } else {
        mEventBeforeOrAboveStartingGestureEvent = false;
      }
    } else {
      for (int i = 0; i < count; i++) {
        if (skipIndex == i) continue;
        sumX += event.getX(i);
        sumY += event.getY(i);
      }
      focusX = sumX / div;
      focusY = sumY / div;
    }
    // Determine average deviation from focal point
    float devSumX = 0, devSumY = 0;
    for (int i = 0; i < count; i++) {
      if (skipIndex == i) continue;
      // Convert the resulting diameter into a radius.
      devSumX += Math.abs(event.getX(i) - focusX);
      devSumY += Math.abs(event.getY(i) - focusY);
    }
    final float devX = devSumX / div;
    final float devY = devSumY / div;
    final float spanX = devX * 2;
    final float spanY = devY * 2;
    final float span;
    if (inAnchoredScaleMode()) {
      span = spanY;
    } else {
      span = (float) Math.hypot(spanX, spanY);
    }
    // Dispatch begin/end events as needed.
    // If the configuration changes, notify the app to reset its current state by beginning
    // a fresh scale event stream.
    final boolean wasInProgress = mInProgress;
    mFocusX = focusX;
    mFocusY = focusY;
    if (!inAnchoredScaleMode() && mInProgress && (span < mMinSpan || configChanged)) {
      mListener.onScaleEnd(this);
      mInProgress = false;
      mInitialSpan = span;
    }
    if (configChanged) {
      mPrevSpanX = mCurrSpanX = spanX;
      mPrevSpanY = mCurrSpanY = spanY;
      mInitialSpan = mPrevSpan = mCurrSpan = span;
    }
    final int minSpan = inAnchoredScaleMode() ? mSpanSlop : mMinSpan;
    if (!mInProgress && span >= minSpan &&
        (wasInProgress || Math.abs(span - mInitialSpan) > mSpanSlop)) {
      mPrevSpanX = mCurrSpanX = spanX;
      mPrevSpanY = mCurrSpanY = spanY;
      mPrevSpan = mCurrSpan = span;
      mPrevTime = mCurrTime;
      mInProgress = mListener.onScaleBegin(this);
    }
    // Handle motion; focal point and span/scale factor are changing.
    if (action == MotionEvent.ACTION_MOVE) {
      mCurrSpanX = spanX;
      mCurrSpanY = spanY;
      mCurrSpan = span;
      boolean updatePrev = true;
      if (mInProgress) {
        updatePrev = mListener.onScale(this);
      }
      if (updatePrev) {
        mPrevSpanX = mCurrSpanX;
        mPrevSpanY = mCurrSpanY;
        mPrevSpan = mCurrSpan;
        mPrevTime = mCurrTime;
      }
    }
    return true;
  }

一堆代码,数学不太好的看起来还真比较艰难,大概就是根据多个触碰点的x坐标算出一个x轴平均值,然后y轴也一样,然后通过Math.hypot(spanX, spanY);算出斜边长,斜边长即为两点之间的距离,然后保存当前的span跟移动过后的span。

最后当我们调用getScaleFactor获取缩放比例的时候,即用现在的span/之前的span:


public float getScaleFactor() {
    if (inAnchoredScaleMode()) {
      // Drag is moving up; the further away from the gesture
      // start, the smaller the span should be, the closer,
      // the larger the span, and therefore the larger the scale
      final boolean scaleUp =
          (mEventBeforeOrAboveStartingGestureEvent && (mCurrSpan < mPrevSpan)) ||
              (!mEventBeforeOrAboveStartingGestureEvent && (mCurrSpan > mPrevSpan));
      final float spanDiff = (Math.abs(1 - (mCurrSpan / mPrevSpan)) * SCALE_FACTOR);
      return mPrevSpan <= 0 ? 1 : scaleUp ? (1 + spanDiff) : (1 - spanDiff);
    }
    return mPrevSpan > 0 ? mCurrSpan / mPrevSpan : 1;
  }

这数学渣真的是硬伤啊~~~

有了android自带的ScaleGestureDetector作为参考,我们能自己实现ScaleGestureDetector吗?? 当然github上大神已经实现了,但是如果没有的话,你能写出来么?

先写到这,未完待续。

您可能感兴趣的文章:Android手势ImageView三部曲 第二部Android手势ImageView三部曲 第一部Android自定义GestureDetector实现手势ImageViewAndroid使用ImageView实现支持手势缩放效果Android ImageView随手势变化动态缩放图片Android手势滑动实现ImageView缩放图片大小Android实现手势控制ImageView图片大小Android通过手势实现的缩放处理实例代码android开发之为activity增加左右手势识别示例android使用gesturedetector手势识别示例分享


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯