[Code Snippets #3] iOS CoreImage Effects

[Code Snippets #3] iOS CoreImage Effects

Subscribe to my newsletter and never miss my upcoming articles

  • Import CoreImage framework on the top of your class:
import CoreImage
  • Declare a few CoreImage default effects:
let CIFilterNames = [
    "CIPhotoEffectChrome",
    "CIPhotoEffectFade",
    "CIPhotoEffectInstant",
    "CIPhotoEffectNoir",
    "CIPhotoEffectProcess",
    "CIPhotoEffectTonal",
    "CIPhotoEffectTransfer",
    "CISepiaTone"
]
  • Inside viewDidLoad():
// Pick an image from the Assets.xcassets folder
var myImg = UIImage(named: "my_image")

// Create a filter
let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: myImg.image!)
let filter = CIFilter(name: "\(CIFilterNames[0])" ) // change '0' into another value to select a CoreImage Effect
filter!.setDefaults()
filter!.setValue(coreImage, forKey: kCIInputImageKey)
let filteredImageData = filter!.value(forKey: kCIOutputImageKey) as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageData, from: filteredImageData.extent)

// Apply effect to the UIImage - and use it as you wish
myImg = UIImage(cgImage: filteredImageRef!)

You can download a free sample Xcode project here .

 
Share this