![](/img/trans.png)
[英]How to place the `UIColor` on `UIImage` at particular (X,Y) position?
[英]How to get x and y position of UIImage in UIImageView?
使用以下擴展名
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.