In my app, I'm displaying an image of a rectangle from the assets library. The image is 100x100 pixels. I'm only using the 1x slot for this asset.
I want to display this image at 300x300 pixels. Doing this using points is quite simple but I can't figure out how to get UIImageView to set the size in pixels.
Alternatively, if I can't set the size in pixels to display, I'd like to get the size in pixels that the image is being displayed.
I have tried using .scale
on the UIImageView and UIImage instances, but it's always 1. Even though I have set constraints to 150 and 300.
Answer: A: Answer: A: Get the Actual Pixels App from the App Store. It's free and will tell you the pixel size of any photo you open.
To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
An iOS point is equivalent to 1/163 of an inch. This size is always the same regardless of the resolution of the phone it is on, and comes from the 163DPI of the original iPhone.
To get size in pixels of UIImageView
:
let widthInPixels = imageView.frame.width * UIScreen.mainScreen().scale let heightInPixels = imageView.frame.height * UIScreen.mainScreen().scale
To get size in pixels of UIImage
:
let widthInPixels = image.size.width * image.scale let heightInPixels = image.size.height * image.scale
Swift 5
Take a Look 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With