在UIImageView中的ScaleAspectFill之后计算图像中的位置

时间:2017-08-18 16:12:56

标签: ios swift uiimageview

我正在UIImageView中加载各种大小的图像。有些图像带有注释,每个注释在图像中都有一个独特的位置。注释坐标相对于原始图像大小。

如何变换坐标以便在调整大小后,注释显示在UIImageView中的相同位置?

我可以使用AVMakeRectWithAspectRatioInsideRect来计算新的排名,但这仅适用于我必须使用的ScaleAspectFit而不是ScaleAspectFill

1 个答案:

答案 0 :(得分:1)

你需要:

  • 计算aspectFill的aspectRatio
  • 通过aspectRatio
  • 乘以注释的x,y坐标
  • 根据视图框外的图像数量调整该点

这是一种方法(为了清晰起见,有点冗长):

func aspectFillPoint(for point: CGPoint, in view: UIImageView) -> CGPoint {

    guard let img = view.image else {
        return CGPoint.zero
    }

    // imgSize will be modified
    var imgSize = img.size

    let viewSize = view.frame.size

    let aspectWidth  = viewSize.width / imgSize.width
    let aspectHeight = viewSize.height / imgSize.height

    // calculate aspectFill ratio
    let f = max(aspectWidth, aspectHeight)

    // scale imgSize
    imgSize.width *= f
    imgSize.height *= f

    // unless aspect ratio of view is the same as image,
    // it will either extend above and below or left and right
    // of the view frame
    let xOffset = (viewSize.width - imgSize.width) / 2.0
    let yOffset = (viewSize.height - imgSize.height) / 2.0

    // scale the original point, and adjust for offsets
    return CGPoint(
        x: (point.x * f) + xOffset,
        y: (point.y * f) + yOffset
        )

}

假设您将图片分配到theImageView,设置为.scaleAspectFill,您可以这样调用:

let annotationPoint = CGPoint(x: 232, y: 148)

var newPoint = aspectFillPoint(for: annotationPoint, in: theImageView)

// Note: newPoint is relative to the View Bounds, so unless the
// imageView is at 0,0 we need to adjust for position
newPoint.x += theImageView.frame.origin.x
newPoint.y += theImageView.frame.origin.y