WPF Geometry幾何圖形數據圖標


相信大家在閱讀WPF相關GitHub開源項目源碼時都會看見一串串這種數據
image這種Geometry數據就是幾何圖形數據

為什么要用Geometry數據做圖標?

有一種做法是使用ttf字體文件代替,不過使用ttf字體文件會出現下面幾個缺點:
1、團隊協作不便於管理
2、需要依賴特定平台
3、無法靈活使用
而使用Geometry的話,我們可以將這些幾何圖形數據存入資源字典ResourceDictionary
通過反射進行靈活使用,團隊開發可共同維護

怎么獲取Geometry數據?

我們進入https://www.iconfont.cn/官網,找到心儀的圖標,點擊F12將鼠標放在該圖標區域,找到網頁元素
image
Path標簽內的d屬性即Geometry數據

如何使用Geometry數據

創建資源字典,並加入命名空間
image
將Geometry數據存入< Geometry x:Key="t_chart" o:Freeze="true" >< /Geometry >標簽內
t_chart即資源名稱key
可能會有小伙伴注意到了o:Freeze這個屬性,下面是MSDN上的原文

A class that derives from Freezable gains the following features:
Special states: a read-only (frozen) state and a writable state.
Thread safety: a frozen Freezable object can be shared across threads.
Detailed change notification: Unlike other DependencyObject objects, a Freezable object provides change notifications when sub-property values change.
Easy cloning: the Freezable class has already implemented several methods that produce deep clones.
翻譯后:
從Freezable派生的類具有以下功能:
特殊狀態:只讀(凍結)狀態和可寫狀態。
線程安全:凍結的Freezable對象可以在線程之間共享。
詳細的更改通知:與其他DependencyObject對象不同,Freezable對象在子屬性值更改時提供更改通知。
易於克隆:Freezable類已經實現了幾種產生深層克隆的方法。

隨后在App.xaml中加入

<ResourceDictionary Source="Resources/Themes/Geometries.xaml" />

這樣我們就可以在全局的XAML代碼中通過{StaticResource t_chart}使用Geometry數據

那么肯定會有小伙伴問了,如果想使用MVVM前后台分離開發怎么辦?(在C#代碼中動態使用Geometry)
下面是C#調用Geometry資源的示例
將資源文件存入靜態類中

namespace Demo.Resources.Themes
{
    public static class LocalTheme
    {
        public static ResourceDictionary Dic = new ResourceDictionary { Source = new Uri(@"Resources/Themes/Geometries.xaml", UriKind.Relative) };
    }
}

使用資源字典(Geometry)LocalTheme.Dic["t_chart"],t_chart即資源字典中的key值

var chart = new HandyControl.Controls.TabItem()
{
	Header="圖表",
	Content = xamlModel
};
chart.SetValue(IconElement.GeometryProperty, (Geometry)LocalTheme.Dic["t_chart"]);

SetValue即設置附加屬性
public void SetValue(DependencyProperty dp, object value);
中的value為Geometry


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM