Skip to content

Instantly share code, notes, and snippets.

@AliSoftware
Created May 26, 2023 16:01
Show Gist options
  • Save AliSoftware/7d2945a3d7153c5cefe65fc78601c287 to your computer and use it in GitHub Desktop.
Save AliSoftware/7d2945a3d7153c5cefe65fc78601c287 to your computer and use it in GitHub Desktop.
A demo of applying CIFilters to Swift Images, trying to apply a glow effect
import SwiftUI
import UIKit
import CoreImage
import PlaygroundSupport
extension CIImage {
convenience init(_ uiImage: UIImage) {
if let cgImage = uiImage.cgImage {
self.init(cgImage: cgImage)
} else {
self.init()
}
}
func bloom(intensity: Float = 1.0, radius: Float = 2) -> CIImage {
let ctx = CIContext()
guard let filter = CIFilter(name: "CIBloom") else { fatalError("Filter Unavailable") }
filter.setValue(self, forKey: kCIInputImageKey)
filter.setValue(intensity, forKey: kCIInputIntensityKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
return filter.outputImage ?? CIImage.empty()
}
func edges(intensity: Float = 1.0) -> CIImage {
let ctx = CIContext()
guard let filter = CIFilter(name: "CIEdges") else { fatalError("Filter Unavailable") }
filter.setValue(self, forKey: kCIInputImageKey)
filter.setValue(intensity, forKey: kCIInputIntensityKey)
return filter.outputImage ?? CIImage.empty()
}
}
extension Image {
init(_ cgImage: CGImage) {
self.init(cgImage, scale: 1.0, orientation: .up, label: Text(""))
}
init(_ uiImage: UIImage) {
guard let cgImage = uiImage.cgImage else { fatalError("Nil CGImage for UIImage") }
self.init(cgImage)
}
init(_ ciImage: CIImage) {
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {
self.init(cgImage, scale: 1.0, orientation: .up, label: Text(""))
} else {
self.init(systemName: "unknown")
}
}
}
struct BorderedSymbol: View {
let symbolName: String
let symbolColor: Color
let borderColor: Color
var body: some View {
let image = UIImage(systemName: symbolName)!
let edged = CIImage(image).edges().bloom()
ZStack {
Image(edged)
.renderingMode(.template)
.foregroundColor(borderColor)
Image(image)
.renderingMode(.template)
.foregroundColor(symbolColor)
}
}
}
let bordered = BorderedSymbol(symbolName: "pin.circle", symbolColor: .orange, borderColor: .blue)
.imageScale(.large)
.scaleEffect(1.0)
.frame(width: 100, height: 100)
PlaygroundPage.current.setLiveView(bordered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment