Misha M
Misha M

Reputation: 11289

iOS: Get displayed image size in pixels

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.

Upvotes: 24

Views: 25125

Answers (2)

Faris
Faris

Reputation: 1236

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!

Upvotes: 3

Code
Code

Reputation: 6251

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

Upvotes: 46

Related Questions