skip to Main Content

I’m trying to change the image scale in a UIImageView, I want it to be smaller and keep its ratio.

I tried cameraPhoto.image?.scale = CGFloat(0.5) but it doesn’t work, i get Cannot assign to property: 'scale' is a get-only property

Anyone knows how to get around this?

Thanks

2

Answers


  1. I think you need to create UIImageView with size of your image and place it on UIScrollView (and disable scroll). Then you can change scale of scroll view.
    https://www.brightec.co.uk/blog/creating-a-zoomable-image-view-in-swift

    Login or Signup to reply.
  2. You can use from this extensions:

    extension UIImage {
        func imageWithSize(size: CGSize) -> UIImage? {  
            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale);
            let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height);
            draw(in: rect)
            
            let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            
            return resultingImage
        }
    
    
        func imageWithScale(scale: CGFloat) -> UIImage? {
            let width = self.size.width * scale
            let height = self.size.height * scale
            return self.imageWithSize(size: CGSize(width: width, height: height))
        }
    }
    
    

    and use this function in your image

    let img = yourImage?.imageWithScale(scale: 0.5)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search