簡體   English   中英

將UIImage設置為UIImageView以節省內存時是否需要調整其大小?

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

UIImage設置為UIImageView ,我知道iOS會自動縮放圖像以使其適合ImageView。 但是,如果我將非常大的圖像文件作為UIImage加載,iOS會自動縮小UIImage的大小(從而節省內存),直到恰好適合ImageView為止嗎?還是我必須對UIImage進行修剪我自己的形象?

如果需要,如何調整UIImage的大小?

設置圖像的大小是可選的,如果不設置圖像大小,則不存在內存節省,圖像將被設置為UIImage視圖的幀大小。 此功能將調整圖像大小。

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
}

在這里,您可以使用上述功能,並將大小設置為CGFloat中所需的寬度和高度。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM