ios – 使用大型UIImage数组时的内存问题导致崩溃(swift)

在我的应用程序中,我有一个图像阵列,可以保存我相机拍摄的所有图像.我正在使用collectionView来显示这些图像.但是,当此图像阵列到达大约20张图像时,它会崩溃.我相信这是由于内存问题..如何以一种内存效率的方式将图像存储在图像阵列中?

Michael Dauterman使用缩略图提供了答案.我希望除此之外还有一个解决方案.也许将图片存储到NSData或CoreData中?

Camera.swift

//What happens after the picture is chosen
func imagePickerController(picker:UIImagePickerController,didFinishPickingMediawithInfo info: [NSObject:AnyObject]){
    //cast image as a string
    let mediaType = info[UIImagePickerControllerMediaType] as! Nsstring
    self.dismissViewControllerAnimated(true,completion: nil)
    //if the mediaType it actually is an image (jpeg)
    if mediaType.isEqualToString(kUTTypeImage as Nsstring as String){
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage

        //Our outlet for imageview
        appraisalPic.image = image

        //Picture taken,to be added to imageArray
        globalPic = image

        //image:didFinish.. if we arent able to save,pass to contextInfo in Error Handling
        if (newMedia == true){
            UIImageWritetoSavedPhotosAlbum(image,self,"image:didFinishSavingWithError:contextInfo:",nil)

        }
    }
}

NewRecord.swift

var imageArray:[UIImage] = [UIImage]()
viewDidLoad(){

    //OUR IMAGE ARRAY WHICH HOLDS OUR PHOTOS,CRASHES AROUND 20th PHOTO ADDED
    imageArray.append(globalPic)

//Rest of NewRecord.swift is code which adds images from imageArray to be presented on a collection view
}

解决方法

我自己的应用程序中遇到了低内存问题,这些问题必须与许多高分辨率UIImage对象一起使用.

解决方案是在imageArray中保存图像的缩略图(这会占用更少的内存),然后显示这些缩略图.如果用户确实需要查看全分辨率图像,您可以允许他们点击图像,然后重新加载&从相机胶卷显示全尺寸UIImage.

这里有一些代码可以让你创建缩略图

// image here is your original image
let size = CGSizeApplyAffineTransform(image.size,CGAffineTransformMakeScale(0.5,0.5))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

UIGraphicsBeginImageContextWithOptions(size,!hasAlpha,scale)
image.drawInRect(CGRect(origin: CGPointZero,size: size))

let scaledImage = UIGraphicsGetimageFromCurrentimageContext()
UIGraphicsEndImageContext()
imageArray.append(scaledImage)

more information about these techniques can be found in this NSHipster article.

斯威夫特4 –

// image here is your original image
let size = image.size.applying(CGAffineTransform(scaleX: 0.5,y: 0.5))
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen

UIGraphicsBeginImageContextWithOptions(size,scale)
image.draw(in: CGRect(origin: .zero,size: size))

let scaledImage = UIGraphicsGetimageFromCurrentimageContext()
UIGraphicsEndImageContext()

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...