shakshi
shakshi

Reputation: 229

Applied image filter to images using core graphics in UITableView

I have used core graphics to display images in greyscale in tableview. But the table is scrolling very slowly.Is there any solution by which i can speed up the scrolling.

Upvotes: 3

Views: 290

Answers (1)

mugx
mugx

Reputation: 10105

You may want to follow these steps:

  1. let's say you have an array of images prepared in your viewDidLoad, called originalImages.
  2. inside your viewDidLoad, you have to scroll all the originalImages applying to each image the gray scale filter and appending the new image inside a new array called grayScaleImages.
  3. use such grayScaleImages as pivot for your UITableViewDataSource (and delegate).

A very rough example might be:

import UIKit

class ViewController:UIViewController, UITableViewDataSource {
    var originalImages:[UIImage]?
    var grayScaleImages:[UIImage]?

    override func viewDidLoad() {
        super.viewDidLoad()

        // load original images
        self.originalImages = [UIImage]() 
        //... load whatever here (eg: from bundle) ...

        // load gray scale images
        self.grayScaleImages = [UIImage]()
        self.originalImages?.forEach { image in
            let grayScaleImage = image.applyGrayScale()
            self.grayScaleImages?.append(grayScaleImage)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.grayScaleImages?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellID", for: indexPath)
        cell.imageView?.image = self.grayScaleImages?[indexPath.row]
        return cell
    }
}

extension UIImage {
    func applyGrayScale() -> UIImage {
        let filter = CIFilter(name: "CIPhotoEffectNoir")!
        filter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
        let output = filter.outputImage!
        let cgImage = CIContext(options: nil).createCGImage(output, from: output.extent)!
        return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
    }
}

Upvotes: 1

Related Questions