Created
January 9, 2024 15:36
-
-
Save lucaswkuipers/d6eee77ee0907ceb674bfc6979aa2c8e to your computer and use it in GitHub Desktop.
Color linear interpolation in Swift (and rgba components extension)
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
import SwiftUI | |
// MARK: - Lerp | |
extension Color { | |
func rgbaLerp(to endColor: Color, _ t: CGFloat) -> Color { | |
let a = rgba | |
let b = endColor.rgba | |
let red = a.r + (b.r - a.r) * t | |
let green = a.g + (b.g - a.g) * t | |
let blue = a.b + (b.b - a.b) * t | |
let alpha = a.a + (b.a - a.a) * t | |
return Color(red: Double(red), green: Double(green), blue: Double(blue), opacity: Double(alpha)) | |
} | |
} | |
// MARK: - RGBA | |
#if canImport(UIKit) | |
import UIKit | |
typealias PlatformColor = UIColor | |
#endif | |
#if canImport(AppKit) | |
import AppKit | |
typealias PlatformColor = NSColor | |
#endif | |
extension Color { | |
var rgba: (r: Double, g: Double, b: Double, a: Double) { | |
var red: CGFloat = 0 | |
var green: CGFloat = 0 | |
var blue: CGFloat = 0 | |
var alpha: CGFloat = 0 | |
var platformColor = PlatformColor(self) | |
#if canImport(AppKit) | |
platformColor = platformColor.usingColorSpace(.deviceRGB) ?? PlatformColor(self) | |
#endif | |
platformColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) | |
return (Double(red), Double(green), Double(blue), Double(alpha)) | |
} | |
var rgb: (r: Double, g: Double, a: Double) { | |
(rgba.r, rgba.g, rgba.b) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment