![](/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.