简体   繁体   中英

How to make fit a larger image into the small image view

I have the image view which has fixed size. But I want to fit every size of image into this without stretching.

I tried this

In method resizeImage, I passed my selected image and size of UIImageView.

 func resizeImage(image: UIImage, size: CGSize) -> UIImage {

        UIGraphicsBeginImageContext(size)
        image.drawInRect(CGRectMake(0, 0, size.width, size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

But this is not working, It is still returning the stretched image.

Please let me know what could be the proper solution.

Thanks

I think what you are looking for is your UIImageView 's contentMode property. Like so:

myImageView.contentMode = .ScaleAspectFit

This value will make sure that when you set the view's image, the image will fill the view as much as possible without stretching the image. You could also use .ScaleAspectFill to completely fill the view, but then your image will be cropped.

Just do this:

imageView.contentMode = .ScaleAspectFill

When you do this, two things happen:

  1. the image in the image view keeps the correct aspect ratio (ie it's not stretched),
  2. The image fills the image view completely. If needed, the center part of the image is cropped. Eg if your image view is square, and the image is a rectangle, then the image will be cropped to a square.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM