Created
June 2, 2026 05:24
-
-
Save bentorkington/a827fff4dc2d8b6a861b94a66a298b7a to your computer and use it in GitHub Desktop.
Flag filters with CoreImage and Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FlagFilter: FPFilter { | |
| 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 { | |
| // todo: this filter never knows which way is 'up' | |
| // consider using CIBlendWithMask if we need to vary the alpha at runtime | |
| return baseImage | |
| .transformed(by: CGAffineTransform( | |
| scaleX: image.extent.width / CGFloat(width), | |
| y: image.extent.height / CGFloat(height))) | |
| .composited(over: image) | |
| } | |
| } | |
| class PrideFlag: FlagFilter { // 🏳️🌈 | |
| let width = 6, height = 1, components = 4 | |
| 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) | |
| } | |
| } | |
| extension CIImage { | |
| func getCenter() -> CIVector { | |
| let extent = self.extent | |
| return CIVector(x: extent.origin.x + extent.size.width / 2, y: extent.origin.y + extent.size.height / 2) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't worry about FPFilter, it's just a protocol from a wider part of one of my apps. Just use FlagFilter as a base class.