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

How to save filtered image in array?

我有一个 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 冻结,图像上的过滤器发生变化。

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

如果图像已经在 self.filtered[indexPath.row] 中,为什么还需要执行 let img1 = self.applyFilterTo(img, filter: self.filtersImages[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
}