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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use {ExtendMode, Gradient, GradientStop, LayoutPoint, LayoutSize, RadialGradient};
pub struct GradientBuilder {
stops: Vec<GradientStop>,
}
impl GradientBuilder {
pub fn new() -> GradientBuilder {
GradientBuilder {
stops: Vec::new(),
}
}
pub fn with_stops(stops: Vec<GradientStop>) -> GradientBuilder {
GradientBuilder { stops }
}
pub fn push(&mut self, stop: GradientStop) {
self.stops.push(stop);
}
pub fn stops(&self) -> &[GradientStop] {
self.stops.as_ref()
}
pub fn gradient(
&mut self,
start_point: LayoutPoint,
end_point: LayoutPoint,
extend_mode: ExtendMode,
) -> Gradient {
let (start_offset, end_offset) = self.normalize(extend_mode);
let start_to_end = end_point - start_point;
Gradient {
start_point: start_point + start_to_end * start_offset,
end_point: start_point + start_to_end * end_offset,
extend_mode,
}
}
pub fn radial_gradient(
&mut self,
center: LayoutPoint,
radius: LayoutSize,
extend_mode: ExtendMode,
) -> RadialGradient {
if radius.width <= 0.0 || radius.height <= 0.0 {
let last_color = self.stops.last().unwrap().color;
self.stops.clear();
self.stops.push(GradientStop { offset: 0.0, color: last_color, });
self.stops.push(GradientStop { offset: 1.0, color: last_color, });
return RadialGradient {
center,
radius: LayoutSize::new(1.0, 1.0),
start_offset: 0.0,
end_offset: 1.0,
extend_mode,
};
}
let (start_offset, end_offset) =
self.normalize(extend_mode);
RadialGradient {
center,
radius,
start_offset,
end_offset,
extend_mode,
}
}
fn normalize(&mut self, extend_mode: ExtendMode) -> (f32, f32) {
let stops = &mut self.stops;
assert!(stops.len() >= 2);
let first = *stops.first().unwrap();
let last = *stops.last().unwrap();
assert!(first.offset <= last.offset);
let stops_delta = last.offset - first.offset;
if stops_delta > 0.000001 {
for stop in stops {
stop.offset = (stop.offset - first.offset) / stops_delta;
}
(first.offset, last.offset)
} else {
stops.clear();
match extend_mode {
ExtendMode::Clamp => {
stops.push(GradientStop { color: first.color, offset: 0.0, });
stops.push(GradientStop { color: first.color, offset: 0.5, });
stops.push(GradientStop { color: last.color, offset: 0.5, });
stops.push(GradientStop { color: last.color, offset: 1.0, });
let offset = last.offset;
(offset - 0.5, offset + 0.5)
}
ExtendMode::Repeat => {
stops.push(GradientStop { color: last.color, offset: 0.0, });
stops.push(GradientStop { color: last.color, offset: 1.0, });
(0.0, 1.0)
}
}
}
}
}