【问题标题】:Zoom and center on UIImage inside UIImageView在 UIImageView 内的 UIImage 上缩放和居中
【发布时间】:2017-10-10 14:27:03
【问题描述】:

我需要帮助来缩放图像然后将其重新居中到给定点。

因此,例如当用户单击名字时:我想将图像缩放并以名字居中。

到目前为止,这是我的代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    guard let _image = self.image else {
        return
    }


    //Get rect of the image inside the ImageView
    let imageRect   = self.getImageRect()

    // Calculate the scale ratio
    let ratioHeight =  _image.size.height / imageRect.size.height
    let ratioWidth  = _image.size.width / imageRect.size.width
    let aspect = fmin(ratioWidth, ratioHeight)

    // get the coordinates (x,y)
    let xA4 = array[indexPath.row].coords[0]
    let yA4 = array[indexPath.row].coords[1]

    // Convert (x,y) into my current plan
    let x  = xA4 / aspect + imageRect.origin.x
    let y  = yA4 / aspect + imageRect.origin.y

    NSLog("xA4 : \(xA4) ------ x : \(x)")
    NSLog("yA4 : \(yA4) ------ y : \(y)")

    //Apply transformation
        var transform =  CGAffineTransform.identity
        transform = transform.translatedBy(x: imageView.center.x - x , y: imageView.center.y - y)
//        transform = transform.scaledBy(x: 2, y: 2)
        self.imageView.layer.setAffineTransform(transform)

    }

问题是图像缩放正确,但它重新居中在错误的位置,而不是我给coord的点

那么我错过了什么?为什么不是缩放或正确的地方?

更新

为了更清楚我是如何使用的,请尝试找出翻译坐标:

  1. 获取显示图像的矩形而不是 图像视图。
  2. 然后找到刻度值
  3. 将服务器发送的坐标转换为与我当前的 imageSize 和位置相匹配的坐标。
  4. 然后重新定位图像

这是正确的吗?因为它不起作用,而且如果我在名字上单击两次,图像会被翻译两次,通常应该是一次。因为它已经在同一个中心在同一个点上。

【问题讨论】:

    标签: ios swift uitableview swift3 uiimage


    【解决方案1】:

    在您的 CODE 2 示例中,您每次都将 transform 替换为新的,因此仅应用最后一次转换。尝试类似:

    var transform = CGAffineTransform(scaleX: 3, y: 3)
    transform = transform.translatedBy(x: coord.x, y: coord.y)
    self.imageView.layer.setAffineTransform(transform)
    

    还要注意应用这些转换的顺序

    【讨论】:

    • 谢谢,但重新居中仍有问题
    【解决方案2】:

    到目前为止,它已被最新版本覆盖,这就是为什么只有 translationX 正在申请。

    你必须像这样使用:

    var transform =  CGAffineTransform.identity
    transform = transform.scaledBy(x: 3, y: 3)
    transform = transform.translatedBy(x: coord.x, y: coord.y)
    self.imageView.layer.setAffineTransform(transform)
    

    【讨论】:

    • 谢谢,但重新定心仍有问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    相关资源
    最近更新 更多