早期 .NET Framework 的開發者為了實作 UI 元件的外圍發光效果,
通常會使用 BitmapEffect
或 OuterGlowBitmapEffect
。
然而,BitmapEffect
是由軟體 render 達成的,一旦大量使用將對系統造成負擔;
隨著 API 與時俱進,新版的 .NET Framework 將不採用 System.Windows.Media.Effects.BitmapEffect
,
取而代之的是支援硬體加速的方案。
因此這些語法若於 .NET Framework 3.5 SP1 之後的版本編譯,可能會得到如下警告訊息 (warning message):
Warning 1 ‘Public Property BitmapEffect() As System.Windows.Media.Effects.BitmapEffect’ is obsolete: ‘Avoid using BitmapEffects as they have very poor performance characteristics. They will be deprecated in a future version. Consider using the UIElement.Effect property and ShaderEffects where appropriate instead.’
內容是大意是為了保持程式碼的可維護性,建議開發者使用較新的 API 作為替代方案。
問題來了,UIElement.Effects
有沒有 OuterGlowBitmapEffect
的替代方案呢?
答案是沒有!
因此我們只能找尋功能性質類似的 API,也就是本次的主題 –
System.Windows.Media.Effects
中的 DropShadowEffect
解說
OuterGlowBitmapEffect
的效果顧名思義,是在指定物件的外圍產生發光效果,
關鍵變數包含顏色 (GlowColor
) 及發光範圍 (GlowSize
)。
而 DropShadowEffect
原本是用來產生陰影的,
相關變數除了顏色 (Color
)之外,還包含陰影偏移 (ShadowDepth
) 及模糊半徑 (BlurRadius
),
因此我們必須將 ShadowDepth
設為 0 、BlurRadius
設定在適當的範圍,
才能達到與 OuterGlowBitmapEffect
同等效果。
範例
以下將示範採用 XAML 及程式化的方式呈現 Button
控制項的兩種效果。
首先使用 XAML 設計 UI 佈局,並於第一、二個按鈕分別插入屬性設定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < Window x:Class = "BitmapEffact.Window1" Title = "BitmapEffect Replacement" Width = "auto" Height = "auto" > < StackPanel > < Button Width = "200" Margin = "15" Name = "button1" VerticalAlignment = "Center" > < Button.BitmapEffect > < OuterGlowBitmapEffect GlowColor = "Salmon" GlowSize = "5" /> </ Button.BitmapEffect > OuterGlowBitmapEffect by XAML </ Button > < Button Width = "200" Margin = "15" Name = "button2" VerticalAlignment = "Center" > < Button.Effect > < DropShadowEffect ShadowDepth = "0" Color = "Salmon" BlurRadius = "10" /> </ Button.Effect > DropShadowEffect by XAML </ Button > < Button Width = "200" Margin = "15" Name = "button3" VerticalAlignment = "Center" >OuterGlowBitmapEffect by C#</ Button > < Button Width = "200" Margin = "15" Name = "button4" VerticalAlignment = "Center" >DropShadowEffect by C#</ Button > </ StackPanel > </ Window > |
接著於 C# 程式碼中為第三、四個按鈕設定效果。
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
namespace BitmapEffact
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
#region OuterGlowBitmapEffect Setting
OuterGlowBitmapEffect myOGBE = new OuterGlowBitmapEffect();
myOGBE.GlowColor = Colors.Violet;
myOGBE.GlowSize = 5;
#endregion
#region DropShadowEffect Setting
DropShadowEffect myDSW = new DropShadowEffect();
myDSW.Color = Colors.Violet;
myDSW.ShadowDepth = 0;
myDSW.BlurRadius = 10;
#endregion
button3.BitmapEffect = myOGBE;
button4.Effect = myDSW;
}
}
}
成果
實做出的效果如圖:
參考資料