2017-10-10 89 views
0

我需要帮助来缩放图像,然后将其重新定位到给定点。
enter image description here在UIImageView中缩放和居中显示UIImage

所以,当用户点击例如名字:我想缩放和居中图像的名字。

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

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

点所以我”错过了?为什么不放大或正确的地方?

UPDATE

为了更清楚如何使用试图找出转换坐标:

  1. 找我显示的图像不是 的ImageView的矩形。
  2. 然后找到比例值
  3. 将服务器发送的坐标转换为与我的curent imageSize和position匹配的坐标。
  4. Then recenter the image

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

回答

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) 

另外要注意的顺序应用这些变换

+0

谢谢你,但仍然有问题,再对 – Chlebta

1

截至目前其最新,多数民众赞成压倒一切的,为什么只有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) 
+0

谢谢你,但仍然有重新定心问题 – Chlebta