forked from nicklockwood/ShapeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaterial+Brightness.swift
More file actions
115 lines (94 loc) · 2.53 KB
/
Material+Brightness.swift
File metadata and controls
115 lines (94 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//
// Material+Brightness.swift
// ShapeScript Lib
//
// Created by Nick Lockwood on 17/04/2022.
// Copyright © 2022 Nick Lockwood. All rights reserved.
//
import Euclid
public extension MaterialProperty {
var brightness: Double {
averageColor.brightness
}
func brightness(over background: Color) -> Double {
averageColor.brightness(over: background)
}
var averageColor: Color {
switch self {
case let .color(color):
return color
case let .texture(texture):
return texture.averageColor ?? .clear
}
}
}
public extension Color {
var brightness: Double {
(r + g + b) / 3
}
func brightness(over background: Color) -> Double {
brightness * a + background.brightness * (1 - a)
}
}
#if canImport(UIKit)
import UIKit
public extension Texture {
var averageColor: Color? {
let image = UIImage(self)
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
defer { UIGraphicsEndImageContext() }
image?.draw(in: rect)
return UIGraphicsGetImageFromCurrentImageContext()?.cgImage?.averageColor
}
}
#elseif canImport(AppKit)
import AppKit
public extension Texture {
var averageColor: Color? {
let image = NSImage(self)
var rect = NSRect(x: 0, y: 0, width: 1, height: 1)
return image?.cgImage(
forProposedRect: &rect,
context: nil,
hints: nil
)?.averageColor
}
}
#else
public extension Texture {
var averageColor: Color? {
Color(0.5, 0.5, 0.5)
}
}
#endif
#if canImport(CoreGraphics)
import CoreGraphics
extension CGImage {
var averageColor: Color? {
let alphaInfo = CGImageAlphaInfo.premultipliedLast
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel
var components = [UInt8](repeating: 0, count: 4)
guard let context = CGContext(
data: &components,
width: 1,
height: 1,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: alphaInfo.rawValue
) else {
return nil
}
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
context.draw(self, in: rect)
return Color(
Double(components[0]) / 255,
Double(components[1]) / 255,
Double(components[2]) / 255,
Double(components[3]) / 255
)
}
}
#endif