0
我一直試圖在調整大小後在uicollectionview中加載圖像。如何使圖像在後臺線程上調整大小,然後在uicollectionview中加載。我嘗試了下面的代碼,但圖像不加載在collectionview中。無法在全局線程中調整大小後在uicollectionview中加載圖像
功能調整
func resizeImage(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 = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
var newImage = UIImage()
DispatchQueue.global().async {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.draw(in: rect)
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
}
return newImage
}
這是cellForItemAt功能:
if let imageView = cell.viewWithTag(499) as? UIImageView {
let image = self.cardImages[indexPath.item]
imageView.image = resizeImage(image: image, targetSize: CGSize(width: 100, height: 100))
}
好的,檢查代碼,讓我知道如果你需要的東西 – Woof
它的工作完美無瑕。非常感謝。 – N4SK