Ios 在应用程序中加载多个保存的图像会减慢速度

Ios 在应用程序中加载多个保存的图像会减慢速度,ios,swift,uiimage,xcode6,Ios,Swift,Uiimage,Xcode6,我正在开发一个应用程序,用户可以保存13个屏幕截图,并以缩略图或全屏图像的形式显示在单个视图上 let fileName:String = self.stickerUsed + ".png" var arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString var pngFileName = arrayPaths.stringByAppend

我正在开发一个应用程序,用户可以保存13个屏幕截图,并以缩略图或全屏图像的形式显示在单个视图上

let fileName:String = self.stickerUsed + ".png"
var arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)
UIImagePNGRepresentation(screenshot).writeToFile(pngFileName, atomically:true)
NSUserDefaults.standardUserDefaults().setObject(fileName, forKey: self.stickerUsed)
NSUserDefaults.standardUserDefaults().synchronize()
以上是我保存图像的方式,以下是我检索图像的方式。这是第一个屏幕截图的代码:

var defaultName:String = "Sticker1.png"
let path = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true)[0] as NSString
let fileName = NSUserDefaults.standardUserDefaults()
    .stringForKey("Sticker1") ?? defaultName
let imagePath = path.stringByAppendingPathComponent(fileName)
let image = UIImage(contentsOfFile: imagePath )

问题是,随着屏幕截图数量的增加,在单个视图中显示它们的速度会变得非常慢。最终,应用程序在显示“已接收内存警告”后崩溃。我是swift和应用程序开发新手。在缩略图中显示所有这些图像的正确方式是什么,而不会减慢速度或崩溃,并且以全分辨率保存图像

以下代码的问题在于,您的所有图像都是全分辨率的:

let image = UIImage(contentsOfFile: imagePath )
最好立即将其缩小,并在加载到内存后制作缩略图:

// This line is still the same
let image = UIImage(contentsOfFile: imagePath )

// Scale the image down: 
let newSize = ... // Defined the new size here
                  // should probably be a good idea to match 
                  // the size of the UIImageView
UIGraphicsBeginImageContext(newSize)
image.drawInRect(CGRect(origin: CGPointZero, size: newSize))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

请参阅更多:

“imagePhoto”是什么?@SameerHussain,对不起,这是多余的代码。你不需要那个。答案被修改了。