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

前端之家收集整理的这篇文章主要介绍了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()
原文链接:https://www.f2er.com/iOS/332633.html

猜你在找的iOS相关文章