Skip to content

Instantly share code, notes, and snippets.

@bentorkington
Created August 1, 2023 06:18
Show Gist options
  • Save bentorkington/e2660fbeac4bf2b30073795d01cf9741 to your computer and use it in GitHub Desktop.
Save bentorkington/e2660fbeac4bf2b30073795d01cf9741 to your computer and use it in GitHub Desktop.
Declarative flag filters with CoreImage
//
// Because you're not going to put yet another asset in your bundle, are you?
//
// Created by Ben Torkington on 1/08/23.
//
import CoreImage
class FlagFilter {
let displayName: String
let baseImage: CIImage
private let components = 4
private let width: Int
private let height: Int
init(name: String, pixelData: [UInt8], width: Int, height: Int) {
self.displayName = name
self.width = width
self.height = height
baseImage = CIImage(
bitmapData: Data(pixelData),
bytesPerRow: width * components,
size: CGSize(width: width, height: height),
format: CIFormat.ARGB8,
colorSpace: CGColorSpaceCreateDeviceRGB()
).samplingNearest()
}
func filter(image: CIImage) -> CIImage {
return baseImage
.transformed(by: CGAffineTransform(
scaleX: image.extent.width / CGFloat(width),
y: image.extent.height / CGFloat(height)))
.composited(over: image)
}
}
class PrideFlag: FlagFilter { // 🏳️‍🌈
let alpha = UInt8(192)
init() {
let palette: [UInt8] = [
alpha, 255, 0, 24, // Vivid Red
alpha, 255, 165, 44, // Deep Saffron
alpha, 255, 255, 65, // Maximum Yellow
alpha, 0, 128, 24, // Ao
alpha, 0, 0, 249, // Blue
alpha, 134, 0, 125, // Philippine Violet
]
super.init(name: "Pride Flag", pixelData: palette, width: 6, height: 1)
}
}
class TransgenderFlag: FlagFilter { // 🏳️‍⚧️
let alpha = UInt8(192)
init() {
let palette: [UInt8] = [
alpha, 85, 205, 252, // Maya Blue
alpha, 247, 168, 184, // Amaranth Pink
alpha, 255, 255, 255, // White
alpha, 247, 168, 184, // Amaranth Pink
alpha, 85, 205, 252, // Maya Blue
]
super.init(name: "Transgender Flag", pixelData: palette, width: 1, height: 5)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment