Skip to content

Commit 06be7b9

Browse files
committed
feat: Color initializer 추가
1 parent d1a80d9 commit 06be7b9

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//
2+
// Color+init.swift
3+
//
4+
//
5+
// Created by Hyun on 9/5/24.
6+
//
7+
8+
import SwiftUI
9+
10+
public extension Color {
11+
12+
/// 16진수 문자열로부터 Color를 초기화합니다.
13+
/// - Parameters:
14+
/// - hex: RGB 형식의 16진수 문자열 (예: "FF0000", "#FF0000")
15+
/// - alpha: 불투명도 값 (0.0 ~ 1.0, 기본값 `1.0`)
16+
init(_ hex: String, alpha: Double = 1) {
17+
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
18+
var int: UInt64 = 0
19+
Scanner(string: hex).scanHexInt64(&int)
20+
let r, g, b: UInt64
21+
switch hex.count {
22+
case 6: // RGB - pattern인 경우
23+
(r, g, b) = (int >> 16, int >> 8 & 0xFF, int & 0xFF)
24+
default:
25+
(r, g, b) = (0, 0, 0) // clear color
26+
}
27+
28+
self.init(
29+
.sRGB,
30+
red: Double(r) / 255,
31+
green: Double(g) / 255,
32+
blue: Double(b) / 255,
33+
opacity: alpha
34+
)
35+
}
36+
37+
/// UInt 타입의 RGB 값으로부터 Color를 초기화합니다.
38+
/// - Parameters:
39+
/// - hex: RGB 형식의 UInt 값 (예: 0xFF0000)
40+
/// - alpha: 불투명도 값 (0.0 ~ 1.0, 기본값 `1.0`)
41+
init(_ hex: UInt, alpha: Double = 1) {
42+
self.init(
43+
.sRGB,
44+
red: Double(hex >> 16) / 255,
45+
green: Double((hex >> 08) & 0xff) / 255,
46+
blue: Double(hex & 0xff) / 255,
47+
opacity: alpha
48+
)
49+
}
50+
}

0 commit comments

Comments
 (0)