Skip to content

Instantly share code, notes, and snippets.

@kovs705
Created March 25, 2024 06:17
Show Gist options
  • Save kovs705/b3dacabcf62d775eb35ee7078604caaf to your computer and use it in GitHub Desktop.
Save kovs705/b3dacabcf62d775eb35ee7078604caaf to your computer and use it in GitHub Desktop.
Color+Ext
//
// Color+Ext.swift
// YourApp
//
// Created by Eugene Kovs on 06.03.2024.
// https://github.com/kovs705
//
import SwiftUI
extension Color {
/// Get color programmatically from Hex in String format
/// - Parameter hex: HEX color: example "#FFFFFF" (white color)
init(hex: String) {
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int: UInt64 = 0
Scanner(string: hex).scanHexInt64(&int)
let a, r, g, b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(
.sRGB,
red: Double(r) / 255,
green: Double(g) / 255,
blue: Double(b) / 255,
opacity: Double(a) / 255
)
}
}
extension UIColor {
// Usage:
/*
color.adjust(-30) // 30% darker color
color.adjust(30) // 30% lighter color
color.lighter(30) // returns lighter color by 30%
color.darker(30) // returns darker color by 30%
*/
//
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return UIColor(red: min(red + percentage/100, 1.0),
green: min(green + percentage/100, 1.0),
blue: min(blue + percentage/100, 1.0),
alpha: alpha)
} else {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment