简体   繁体   中英

Is there a need to resize a UIImage when setting it to an UIImageView to conserve memory?

When setting a UIImage to a UIImageView , I know that iOS automatically scales the image so that it fits within the ImageView. However, if I am loading a very large image file as a UIImage , will iOS automatically cut down the size of the UIImage (and therefore conserving memory) until it is just enough to fit the ImageView?Or do I have to implement the trimming of the image myself?

How do I trim the size of the UIImage if it is needed to do so?

It's optional to set the size of the image , the memory conservation will not be there if there if you set the size or not.Image will be set into the frame size of UIImage view. This function will do the resizing of the image.

func ResizeImageToRequired(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size

let widthRatio  = targetSize.width  / image.size.width
let heightRatio = targetSize.height / image.size.height

// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
    newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
    newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
}

// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)

// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return newImage
}

here you can use the above function and set the size to required Width and Height in CGFloat.

 self.ResizeImageToRequired(UIImage(named: "yourImageName")!, targetSize:      CGSizeMake("width", "height"))

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