如何在数组中保存过滤后的图像?

时间:2016-06-03 10:38:17

标签: ios swift uicollectionview core-image imagefilter

我有一个UICollectionView(水平)并在那里,在单元格中,使用应用过滤器的图像。

我这样做了:

var filtered = [Int: UIImage]()
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("filterCell", forIndexPath: indexPath) as! filterCell

    let op1 = NSBlockOperation { () -> Void in
        let img = self.image!
        let img1 = self.applyFilterTo(img, filter: self.filtersImages[indexPath.row])

        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in

            if let filtered = self.filtered[indexPath.row] {
                cell.imageView.image = self.filtered[indexPath.row]
            } else {
                self.filtered[indexPath.row] = img1
                cell.imageView.image = self.filtered[indexPath.row]

            }
        })
    }

    self.queue!.addOperation(op1);

    return cell
}

其中:

var myFilter = CIFilter()
func applyFilterTo(image: UIImage, filter: String) -> UIImage {
    let sourceImage = CIImage(image: image)

    myFilter = CIFilter(name: filter)!
    myFilter.setDefaults()

    myFilter.setValue(sourceImage, forKey: kCIInputImageKey)

    let context = CIContext(options: nil)

    let outputCGImage = context.createCGImage(myFilter.outputImage!, fromRect: myFilter.outputImage!.extent)

    let newImage = UIImage(CGImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)

    return newImage
}

所以这里的原则是将我的过滤器应用于图像,将其保存在我的字典中,然后再滚动加载来自字典的图像。但它仍然需要图像,应用过滤器,稍后才会显示它。因此,在滚动时,我的UICollectionView会冻结,图像上的过滤器会发生变化。

我做错了什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果图片已在let img1 = self.applyFilterTo(img, filter: self.filtersImages[indexPath.row])

,您需要self.filtered[indexPath.row]

所以我认为你应该检查if let filtered = self.filtered[indexPath.row] {,如果没有,那就开始过滤它。

对于您的代码,它将是这样的:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("filterCell", forIndexPath: indexPath) as! filterCell

    if let filtered = self.filtered[indexPath.row] {
      cell.imageView.image = filtered
    } else {
      let op1 = NSBlockOperation { () -> Void in
        let img = self.image!
        let img1 = self.applyFilterTo(img, filter: self.filtersImages[indexPath.row])

        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
          self.filtered[indexPath.row] = img1
          cell.imageView.image = self.filtered[indexPath.row]
        })
      }

      self.queue!.addOperation(op1);
    }

  return cell
}