在方面适合后从 UIImageView 获取图像的宽度和高度
Posted
技术标签:
【中文标题】在方面适合后从 UIImageView 获取图像的宽度和高度【英文标题】:Getting width and height of image from UIImageView after aspect fit 【发布时间】:2018-11-25 09:25:14 【问题描述】:我试图从 UIImageView 中获取图像的宽度和高度,之后它被缩放到适合宽高比。这就是我得到它的宽度和高度的方式:
let imageHeight = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).height
let imageWidth = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).width
let imageYposition = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).origin.y
let imageXposition = AVMakeRect(aspectRatio: (transferImage.size), insideRect: imageView.frame).origin.x
显然,这给了我宽度和高度。但是,在尝试将 UIView 调整为相同尺寸后,它们的尺寸不同。这就是我如何将 UIView 设置为图像的宽度和高度:
boundariesRectangle.frame = CGRect(x: imageXposition, y: imageYposition, width: imageWidth, height: imageHeight)
会发生这样的事情:
【问题讨论】:
您可以在情节提要中手动设置。这样更容易 【参考方案1】:试试这个:
guard let image = imageView.image else return
// Calculate the scaled size of the image
let scaledRect = AVMakeRect(aspectRatio: image.size, insideRect: imageView.bounds)
// Create the overlay view
let overlayView = UIView(frame: .zero)
overlayView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
overlayView.translatesAutoresizingMaskIntoConstraints = false
// Add the overlay
// To use relate 2 views by auto-layout constraints, they must have the
// same parent view
imageView.superView!.addSubview(overlayView)
overlayView.widthAnchor.constraint(equalToConstant: scaledRect.width).isActive = true
overlayView.heightAnchor.constraint(equalToConstant: scaledRect.height).isActive = true
overlayView.centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true
overlayView.centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true
【讨论】:
以上是关于在方面适合后从 UIImageView 获取图像的宽度和高度的主要内容,如果未能解决你的问题,请参考以下文章
UIImageView 上的方面适合在 UITableView 单元格中留下大量空白