美文网首页自定义控件
支持任意手势动作的图片

支持任意手势动作的图片

作者: 豆沙包67 | 来源:发表于2015-09-17 17:30 被阅读249次

效果预览

支持图片的放大缩小,旋转操作。

效果预览

原理实现

先认识了解处理触摸事件的处理。

  • 以双击的位置为中心进行放大缩小操作;
  • 根据两指之间的距离与初识距离距离比较,进行放大和缩小操作;
  • 根据两指之间的arctan值,计算角度进行旋转。

源码实现

缩放:
    @Override
        public void setScale(float scale, float focalX, float focalY,
                             boolean animate) {
            ImageView imageView = getImageView();
    
            if (null != imageView) {
                // Check to see if the scale is within bounds
                if (scale < mMinScale || scale > mMaxScale) {
                    LogManager
                            .getLogger()
                            .i(LOG_TAG,
                                    "Scale must be within the range of minScale and maxScale");
                    return;
                }
    
                if (animate) {
                    imageView.post(new AnimatedZoomRunnable(getScale(), scale,
                            focalX, focalY));
                } else {
                    mSuppMatrix.setScale(scale, scale, focalX, focalY);
                    checkAndDisplayMatrix();
                }
            }
        }
旋转:
 private boolean doRotate(MotionEvent ev) {
        //Calculate the angle between the two fingers
        float deltaX = ev.getX(0) - ev.getX(1);
        float deltaY = ev.getY(0) - ev.getY(1);
        double radians = Math.atan(deltaY / deltaX);
        //Convert to degrees
        int degrees = (int) (radians * 180 / Math.PI);
        /*
         * Must use getActionMasked() for switching to pick up pointer events.
         * These events have the pointer index encoded in them so the return
         * from getAction() won't match the exact action constant.
         */
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                mLastAngle = degrees;
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mLastAngle = degrees;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                upRotate();
                mLastAngle = degrees;
                break;
            case MotionEvent.ACTION_MOVE:
                int degreesValue = degrees - mLastAngle;
                if (degreesValue > 45) {
                    //Going CCW across the boundary
                    rotate(-5);
                } else if (degreesValue < -45) {
                    //Going CW across the boundary
                    rotate(5);
                } else {
                    //Normal rotation, rotate the difference
                    rotate(degreesValue);
                }
                //Save the current angle
                mLastAngle = degrees;
                break;
        }
        return true;
    }

只贴了部分关键部分代码。

完整代码

相关文章

网友评论

    本文标题:支持任意手势动作的图片

    本文链接:https://www.haomeiwen.com/subject/sxybcttx.html