将UIImageView触摸坐标转换为UIImage坐标Aspect Fill

时间:2017-10-20 09:43:20

标签: ios iphone swift uiimageview uiimage

我已在我的应用程序中实现了此代码

Converting UIImageView Touch Coordinates to UIImage Coordinates

这段代码就像魅力一样,但是我尝试做同样的事情但是使用Aspect Fill,据我所知de代码将不起作用,因为如果Image较小则会扩展得更大,所以我'在纵横比与图像不同的情况下,没有看到部分图像。

这是我实施的代码:

private func pointConversion(point: CGPoint) -> CGPoint {

    if let image = self.imageView.image {
        let percentX = point.x / self.imageView.frame.size.width
        let percentY = point.y / self.imageView.frame.size.height
        return CGPoint(x: image.size.width * percentX , y: image.size.height * percentY)
    }
    return CGPoint(x: 0, y: 0)
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

以下情况适用于填充视图的图像小于至少一个维度的视图的情况。不确定是否遇到两个图像尺寸都大于目标视图的测试:

func mapPointThroughAspectFill(uiViewPoint:CGPoint)->CGPoint
// Maps a point from the coordinate space of our UIView into the space of the image
// which AspectFills that UIView
{
    let imageWidth = imageView!.image!.size.width
    let imageHeight = imageView!.image!.size.height
    let xScale = imageView!.bounds.size.width / imageWidth
    let yScale = imageView!.bounds.size.height / imageHeight
    var x, y,  o:CGFloat

    if (xScale>yScale) {
        // scale vertically from the center for height-pegged images
        o = (imageView.bounds.size.height - (imageHeight*xScale))/2;
        x = uiViewPoint.x / xScale;
        y = (uiViewPoint.y-o) / xScale;
    } else {
        // scale horizontally from the center for width-pegged images
        o = (imageView.bounds.size.width - (imageWidth*yScale))/2;
        x = (uiViewPoint.x-o) / yScale;
        y = uiViewPoint.y / yScale;
    }
    return CGPoint(x: x, y: y)
}