在我的应用中,我在资源库中显示一个矩形图像。图像为100x100像素。我只使用这个资产的1x插槽。
我想以300x300像素显示此图像。使用点进行此操作非常简单,但我无法弄清楚如何让UIImageView设置像素大小。
或者,如果我无法设置要显示的像素大小,我希望获得显示图像的像素大小。
我尝试在UIImageView和UIImage实例上使用.scale
,但它始终为1.尽管我已将约束设置为150和300.
答案 0 :(得分:28)
获取UIImageView
的像素大小:
let widthInPixels = imageView.frame.width * UIScreen.mainScreen().scale
let heightInPixels = imageView.frame.height * UIScreen.mainScreen().scale
获取UIImage
的像素大小:
let widthInPixels = image.size.width * image.scale
let heightInPixels = image.size.height * image.scale
答案 1 :(得分:0)
雨燕5
看看here
// This extension to save ImageView as UImage
extension UIView {
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
// this extension to resize image
extension UIImage {
func resizeImage(targetSize: CGSize) -> UIImage {
let size = self.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
let newSize = widthRatio > heightRatio ? CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
// This extension will display image with 300X300 pixels
extension UIImage {
func Size300X300() -> UIImage? {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
let image = imageView.asImage()
let newImage = image.resizeImage(targetSize: CGSize(width:300, height: 300))
return newImage
}
}
let image = YOURIMAGE.Size300X300() imageView.image = image!