簡體   English   中英

如何在 UIImageView 中獲得 UIImage 的 x 和 y position?

[英]How to get x and y position of UIImage in UIImageView?

當我們使用 scaleAspectFill 將其設置在 UIImageView 中時,我想獲得 UIImage 的原始 x 和 y position。

正如我們在 scaleAspectFill 中所知道的,某些部分被剪裁了。 因此,根據我的要求,我想獲得 x 和 y 值(可能是 - 我不知道的值。)。

這是來自畫廊的原始圖片

原始圖像

現在我將上面的圖像設置為我的應用程序視圖。

在我看來剪輯的圖像

所以在上述情況下,我想得到它隱藏的 x, y position 被剪裁的圖像。

誰能告訴我如何獲得它?

使用以下擴展名

extension UIImageView {

    var imageRect: CGRect {
        guard let imageSize = self.image?.size else { return self.frame }

        let scale = UIScreen.main.scale

        let imageWidth = (imageSize.width / scale).rounded()
        let frameWidth = self.frame.width.rounded()

        let imageHeight = (imageSize.height / scale).rounded()
        let frameHeight = self.frame.height.rounded()

        let ratio = max(frameWidth / imageWidth, frameHeight / imageHeight)
        let newSize = CGSize(width: imageWidth * ratio, height: imageHeight * ratio)
        let newOrigin = CGPoint(x: self.center.x - (newSize.width / 2), y: self.center.y - (newSize.height / 2))
        return CGRect(origin: newOrigin, size: newSize)
    }

}

用法

let rect = imageView.imageRect
print(rect)

界面測試

let testView = UIView(frame: rect)
testView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
imageView.superview?.addSubview(testView)

使用以下擴展在 ImageView 中找出 Image 的准確細節。

extension UIImageView {
    var contentRect: CGRect {
        guard let image = image else { return bounds }
        guard contentMode == .scaleAspectFit else { return bounds }
        guard image.size.width > 0 && image.size.height > 0 else { return bounds }

        let scale: CGFloat
        if image.size.width > image.size.height {
            scale = bounds.width / image.size.width
        } else {
            scale = bounds.height / image.size.height
        }

        let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        let x = (bounds.width - size.width) / 2.0
        let y = (bounds.height - size.height) / 2.0

        return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}

如何測試

let rect = imgTest.contentRect
print("Image rect:", rect)

如果你想像畫廊中顯示的那樣顯示圖像,那么你可以使用約束“H:|[v0]|” 和 "V:|[v0]|" 並在 imageview 中使用 .aspectFit

如果你想要圖像大小,你可以使用 imageView.image!.size 並計算被剪切的圖像量。 在 aspectFill 中,寬度與屏幕寬度匹配,因此高度增加。 所以我想你可以找到有多少圖像被切割。

試試這個庫ImageCoordinateSpace

我不確定它是否適合您,但它具有將 CGPoint 從圖像坐標轉換為任何視圖坐標的功能,反之亦然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM