小程序通过计算两手指之间距离实现图片预览缩放移动

发布时间:2024年01月16日

一、实现思路:
通过修改imageView的margin-left和margin-top来改变图片的位置以实现图片的单指移动效果和所有操作结束松手后的回弹效果。修改imageView的宽和高以实现图片放大缩小的效果,且需要同时修改其margin-left和margin-top使图片能以【两手指的中间点为原点】缩放。

二、实现
用到margin来改变图片的位置,给imageView设置样式的时候就不是单单写个AspectFit,需要计算出图片为了展示出AspectFit的效果所需的宽高和margin。

三、示例代码
xml代码:

<view class="container">
  <image class="img" src="/assets/images/longpress-image-scan/wx-qr-code.jpg" data-src="/assets/images/longpress-image-scan/wx-qr-code.jpg" bind:tap="previewImage" mode="widthFix" />
  <view class="large-pic" wx:if="{{isPreview}}">
    <scroll-view scroll-y="true" scroll-x="true" class = "imageScroll" style="width:{{img_view_width}}px;height:{{img_view_height}}px" bind:tap="_imgClose">
      <image src="{{recogImg}}" class="img" mode="aspectFit" 
          catchload="_imgLoadEvent"
          catchtouchstart='_touchStartEvent'
          catchtouchmove='_touchMoveEvent'
          catchtouchend='_touchEndEvent'
          catchtouchcancel='_touchEndEvent'  
          style="width: {{ imgWidth }}px;height: {{ imgHeight }}px;margin-top:{{marginTop}}px;margin-left:{{marginLeft}}px;"></image>
    </scroll-view>
  </view>
</view>

js代码:

var lastTouchPoint = { x: 0, y: 0 };
var newDist = 0;
var oldDist = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isPreview: false,
    rpxR: "",
    img_view_width: "",//scrollview的宽
    img_view_height: "",//scrollview的高
    marginTop: 0,//图片aspectFit显示时顶部的间距
    marginLeft: 0,//图片aspectFit显示时左边的间距
    srcMarginTop: 0,//图片未被缩放时顶部的间距
    srcMarginLeft: 0,//图片未被缩放时左边的间距
    srcWidth: 0,//图片未被缩放时的高
    srcHeight: 0,//图片未被缩放时的宽
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //根据传入的值设置title
    wx.setNavigationBarTitle({
      title: "图片缩放"
    })
    //给标题和按钮文字赋值
    this.setData({
      rpxR: getApp().globalData.rpxR,
    })
  },
  /** 预览图片 */
  previewImage(e){
    const {src} = e.currentTarget.dataset
    this.setData({
      isPreview: true,
      exampleImageName: src
    })
    this.setData({
      recogImg: this.data.exampleImageName
    })
  /**
   * 这里计算图片以AspectFill方式填充所需的宽、高、margin-left、margin-top数值
   */
    wx.getImageInfo({
      src: this.data.exampleImageName,
      complete: (res) => {
        console.log(res);
        let imageWidth = res.width;
        let imageHeight = res.height;
        let scrollWidth = getApp().globalData.clientWidth;
        let scrollHeight = getApp().globalData.clientHeight;
        // let scrollHeight = 430 / this.data.rpxR;
        //图片显示在view中的宽高度
        var scaleWidth = 0;
        var scaleHeight = 0; 
        //计算图片居中显示需要的margin
        var mLeft = 0;
        var mTop = 0;
        if (imageWidth / imageHeight > scrollWidth / scrollHeight) {
          //图片比较宽,宽度填充
          mLeft = 0;
          mTop = (scrollHeight - (scrollWidth / imageWidth) * imageHeight) * 0.5;
          scaleWidth = scrollWidth;
          scaleHeight = imageHeight * (scrollWidth / imageWidth);
        } else {
          //图片比较长,长度填充
          mTop = 0;
          mLeft = (scrollWidth - (scrollHeight / imageHeight) * imageWidth) * 0.5;
          scaleHeight = scrollHeight;
          scaleWidth = imageWidth * (scrollHeight / imageHeight);
        }
        // console.log(mLeft)
        // console.log(mTop)
        this.setData({
          img_view_width: scrollWidth,
          img_view_height: scrollHeight,
          imgWidth: scaleWidth,
          imgHeight: scaleHeight,
          marginLeft: mLeft,
          srcMarginLeft: mLeft,
          marginTop: mTop,
          srcMarginTop: mTop,
          srcWidth: scaleWidth,
          srcHeight: scaleHeight,
        })
      }
    })
  },
  /**
   * 图片加载完成方法
   */
  _imgLoadEvent: function (event) {
    lastTouchPoint = { x: 0, y: 0 };
    
  },
  /**
     * 触摸开始事件
     */
  _touchStartEvent: function () {
    lastTouchPoint = { x: 0, y: 0 }
    oldDist = 0
  },
  /**
   * 手指移动事件
   */
  _touchMoveEvent: function (e) {
    //单指移动事件
    if (e.touches.length == 1) {
      if (lastTouchPoint.x == 0 && lastTouchPoint.y == 0) {
        lastTouchPoint.x = e.touches[0].clientX
        lastTouchPoint.y = e.touches[0].clientY
      } else {
        var xOffset = e.touches[0].clientX - lastTouchPoint.x
        var yOffset = e.touches[0].clientY - lastTouchPoint.y
        this.setData({
          marginTop: this.data.marginTop + yOffset,
          marginLeft: this.data.marginLeft + xOffset,
        })
        lastTouchPoint.x = e.touches[0].clientX
        lastTouchPoint.y = e.touches[0].clientY
      }
      // console.log(this.data.marginTop)
    }
    //双指缩放事件
    if (e.touches.length == 2) {
      if (oldDist == 0) {
        oldDist = this._spacing(e);
      } else {
        newDist = this._spacing(e);
        if (newDist > oldDist + 1) {
          this._zoom(newDist / oldDist, e);
          oldDist = newDist;
        }
        if (newDist < oldDist - 1) {
          this._zoom(newDist / oldDist, e);
          oldDist = newDist;
        }
      }
    }
  },
  /**
   * 触摸事件结束
   */
  _touchEndEvent: function () {
    //开始回弹
    this._reboundAnimation();
  },
  /**
   * 计算x轴上的双指中心点比例
   */
  _calcXRatio: function (event) {
    var xRatio = ((event.touches[0].clientX + event.touches[1].clientX) / 2 - this.data.marginLeft) / this.data.imgWidth
    return xRatio
  },
  /**
   * 计算y轴上的双指中心点比例
   */
  _calcYRatio: function (event) {
    var yRatio = ((event.touches[0].clientY + event.touches[1].clientY) / 2 - this.data.marginTop) / this.data.imgHeight
    return yRatio
  },
  /**
   * 双指缩放
   */
  _zoom: function (f, event) {
    var xRatio = this._calcXRatio(event)
    var yRatio = this._calcYRatio(event)
    if (this.data.imgWidth <= this.data.view_width && f < 1) {
      var ratio = this.data.view_width / this.data.imgWidth
      this.setData({
        imgWidth: this.data.imgWidth * ratio,
        imgHeight: this.data.imgHeight * ratio
      })
      return;
    }
    if (this.data.imgHeight <= this.data.view_height && f < 1) {
      var ratio = this.data.view_height / this.data.imgHeight
      this.setData({
        imgWidth: this.data.imgWidth * ratio,
        imgHeight: this.data.imgHeight * ratio
      })
      return;
    }
    this.setData({
      //此处的ratio为双指中心点在图片的百分比
      marginLeft: this.data.marginLeft + xRatio * this.data.imgWidth * (1 - f),
      marginTop: this.data.marginTop + yRatio * this.data.imgHeight * (1 - f),
      imgWidth: this.data.imgWidth * f,
      imgHeight: this.data.imgHeight * f,
    })
    // console.log(this.data.marginTop)
  },
  /**
   * 计算两指间距
   */
  _spacing: function (event) {
    var x = event.touches[0].clientX - event.touches[1].clientX;
    var y = event.touches[0].clientY - event.touches[1].clientY;
    return Math.sqrt(x * x + y * y);
  },
  /**
   * 边界的回弹动画
   */
  _reboundAnimation: function () {
    if (this.data.imgWidth / this.data.srcWidth < 1) {
      //缩放比例已经小于1了,直接还原
      this.setData({
        marginLeft: this.data.srcMarginLeft,
        marginTop: this.data.srcMarginTop,
        imgWidth: this.data.srcWidth,
        imgHeight: this.data.srcHeight,
      })
      return ;
    }
    
    //图片已铺满宽或高
    if (this.data.imgWidth > this.data.img_view_width && this.data.marginLeft > 0) {
      //图片宽度已铺满scrollViewWidth且被拉至最左边
      this.setData({
        marginLeft: 0
      })
    }
    if (this.data.imgWidth > this.data.img_view_width && (this.data.marginLeft + this.data.imgWidth) < this.data.img_view_width) {
      //图片宽度已铺满scrollViewWidth且被拉至最右边
      this.setData({
        marginLeft: this.data.img_view_width - this.data.imgWidth
      })
    }
    if (this.data.imgHeight > this.data.img_view_height && this.data.marginTop > 0) {
      //图片高度已铺满scrollViewHeight且被拉至最顶部
      this.setData({
        marginTop: 0
      })
    }
    if (this.data.imgHeight > this.data.img_view_height && (this.data.marginTop + this.data.imgHeight) < this.data.img_view_height) {
      //图片高度已铺满scrollViewHeight且被拉至最底部
      this.setData({
        marginTop: this.data.img_view_height - this.data.imgHeight
      })
    }
    //图片未铺满宽或高
    if (this.data.imgHeight <= this.data.img_view_height) {
      //图片高未铺满scrollViewHeight,垂直居中
      this.setData({
        marginTop: (this.data.img_view_height - this.data.imgHeight) * 0.5
      })
    }
    if (this.data.imgWidth <= this.data.img_view_width) {
      //图片宽未铺满scrollViewWidth,水平居中
      this.setData({
        marginLeft: (this.data.img_view_width - this.data.imgWidth) * 0.5
      })
    }
    
  },
  _imgClose(){
    this.setData({isPreview: false})
  }
})

wxss代码:

.large-pic{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
.imageScroll {
  width: 100%;
  height: 430rpx;
  position: fixed;
  background-color: #000;
}
.img {
  position: absolute;
  display: block;
  background-color: #000;
  text-align: center;
}
文章来源:https://blog.csdn.net/qq_45290368/article/details/135629575
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。