-
Notifications
You must be signed in to change notification settings - Fork 823
Expand file tree
/
Copy pathSvgIcon.cs
More file actions
196 lines (169 loc) · 7.09 KB
/
SvgIcon.cs
File metadata and controls
196 lines (169 loc) · 7.09 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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using Avalonia;
using Avalonia.Automation;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Styling;
namespace UniGetUI.Avalonia.Views.Controls;
/// <summary>
/// Lightweight SVG icon renderer that uses Avalonia's native geometry engine
/// instead of SkiaSharp's SVG module (which is broken on some macOS configurations).
/// Supports single-path and multi-path SVGs with a uniform viewBox.
/// </summary>
public class SvgIcon : Control
{
public SvgIcon()
{
AutomationProperties.SetAccessibilityView(this, AccessibilityView.Raw);
}
public static readonly StyledProperty<string?> PathProperty =
AvaloniaProperty.Register<SvgIcon, string?>(nameof(Path));
public static readonly StyledProperty<IBrush?> ForegroundProperty =
AvaloniaProperty.Register<SvgIcon, IBrush?>(nameof(Foreground),
defaultValue: null, inherits: true);
public string? Path
{
get => GetValue(PathProperty);
set => SetValue(PathProperty, value);
}
private IBrush? _localForeground;
public IBrush? Foreground
{
get => GetValue(ForegroundProperty);
set => SetValue(ForegroundProperty, value);
}
private readonly List<Geometry> _geometries = new();
private double _viewBoxWidth = 24, _viewBoxHeight = 24;
static SvgIcon()
{
AffectsRender<SvgIcon>(ForegroundProperty);
AffectsMeasure<SvgIcon>(PathProperty);
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
if (Application.Current is { } app)
app.ActualThemeVariantChanged += OnThemeChanged;
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
if (Application.Current is { } app)
app.ActualThemeVariantChanged -= OnThemeChanged;
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == ForegroundProperty)
{
_localForeground = change.Priority < BindingPriority.Style
? change.NewValue as IBrush
: null;
}
else if (change.Property == PathProperty)
LoadSvg(change.NewValue as string);
}
private void OnThemeChanged(object? sender, EventArgs e) => InvalidateVisual();
private void LoadSvg(string? uri)
{
_geometries.Clear();
_viewBoxWidth = 24;
_viewBoxHeight = 24;
if (string.IsNullOrEmpty(uri))
{
InvalidateVisual();
return;
}
try
{
using Stream stream = AssetLoader.Open(new Uri(uri));
XDocument doc = XDocument.Load(stream);
XElement? svg = doc.Root;
if (svg is null) return;
string? vb = svg.Attribute("viewBox")?.Value;
if (vb != null)
{
var parts = vb.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 4 &&
double.TryParse(parts[2], System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double w) &&
double.TryParse(parts[3], System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double h))
{
_viewBoxWidth = w;
_viewBoxHeight = h;
}
}
else if (
double.TryParse(svg.Attribute("width")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double svgW) &&
double.TryParse(svg.Attribute("height")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double svgH))
{
_viewBoxWidth = svgW;
_viewBoxHeight = svgH;
}
XNamespace ns = "http://www.w3.org/2000/svg";
foreach (XElement el in doc.Descendants(ns + "path"))
{
string? d = el.Attribute("d")?.Value;
if (!string.IsNullOrEmpty(d))
{
try { _geometries.Add(Geometry.Parse(d)); }
catch { /* skip malformed path data */ }
}
}
foreach (XElement el in doc.Descendants(ns + "ellipse"))
{
if (double.TryParse(el.Attribute("cx")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double cx) &&
double.TryParse(el.Attribute("cy")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double cy) &&
double.TryParse(el.Attribute("rx")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double rx) &&
double.TryParse(el.Attribute("ry")?.Value, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double ry))
{
_geometries.Add(new EllipseGeometry(new Rect(cx - rx, cy - ry, rx * 2, ry * 2)));
}
}
}
catch
{
// Silently ignore missing or unreadable assets
}
InvalidateMeasure();
InvalidateVisual();
}
private static readonly IBrush _darkFg = new SolidColorBrush(Color.Parse("#E8E8E8"));
private static readonly IBrush _lightFg = new SolidColorBrush(Color.Parse("#1E1E1E"));
private static IBrush LookupThemeForeground() =>
Application.Current?.ActualThemeVariant == ThemeVariant.Dark
? _darkFg
: _lightFg;
protected override Size MeasureOverride(Size availableSize)
{
double w = double.IsInfinity(availableSize.Width) ? _viewBoxWidth : availableSize.Width;
double h = double.IsInfinity(availableSize.Height) ? _viewBoxHeight : availableSize.Height;
return new Size(w, h);
}
public override void Render(DrawingContext context)
{
if (_geometries.Count == 0) return;
IBrush brush = _localForeground ?? LookupThemeForeground();
double scaleX = Bounds.Width / _viewBoxWidth;
double scaleY = Bounds.Height / _viewBoxHeight;
double scale = Math.Min(scaleX, scaleY);
double offsetX = (Bounds.Width - _viewBoxWidth * scale) / 2;
double offsetY = (Bounds.Height - _viewBoxHeight * scale) / 2;
using var _ = context.PushTransform(
Matrix.CreateTranslation(offsetX, offsetY) * Matrix.CreateScale(scale, scale));
foreach (Geometry geo in _geometries)
context.DrawGeometry(brush, null, geo);
}
}