在 WPF 啟動界面中心加載 GIF 動圖
在 WPF 啟動界面中心加載 GIF 動圖可以通過多種方式實現。下面我將提供一個完整的解決方案,包括使用第三方庫和純 WPF 實現兩種方法。
方法一:使用 WpfAnimatedGif 庫(推薦)
這是最簡單可靠的方法,使用專門處理 GIF 動畫的庫。
實現步驟:
-
安裝 NuGet 包
Install-Package WpfAnimatedGif
-
創建啟動窗口 (SplashScreen.xaml)
<Window x:Class="YourNamespace.SplashScreen"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:gif="http://wpfanimatedgif.codeplex.com"WindowStyle="None" AllowsTransparency="True"Background="Transparent"WindowStartupLocation="CenterScreen"Width="400" Height="400"><Grid><!-- 背景 --><Border CornerRadius="20" Background="#1E1E1E" Opacity="0.9"BorderBrush="#3F3F46" BorderThickness="1"><!-- 陰影效果 --><Border.Effect><DropShadowEffect BlurRadius="20" ShadowDepth="0" Color="#000000" Opacity="0.5"/></Border.Effect></Border><!-- 中心 GIF 動畫 --><Image x:Name="LoadingGif" gif:ImageBehavior.AnimatedSource="/Assets/loading.gif"gif:ImageBehavior.AutoStart="True"Width="200" Height="200"HorizontalAlignment="Center" VerticalAlignment="Center"/><!-- 狀態文本 --><TextBlock x:Name="StatusText" Text="正在加載..." Foreground="#E0E0E0" FontSize="16"HorizontalAlignment="Center" VerticalAlignment="Bottom"Margin="0,0,0,30"/></Grid>
</Window>
- 在代碼中更新狀態文本 (SplashScreen.xaml.cs)
using System.Windows;namespace YourNamespace
{public partial class SplashScreen : Window{public SplashScreen(){InitializeComponent();}// 更新狀態文本的方法public void UpdateStatus(string message){StatusText.Text = message;}}
}
- 在 App.xaml.cs 中使用啟動窗口
using System;
using System.Threading.Tasks;
using System.Windows;namespace YourNamespace
{public partial class App : Application{private SplashScreen _splashScreen;protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// 創建并顯示啟動窗口_splashScreen = new SplashScreen();_splashScreen.Show();// 異步初始化應用Task.Run(() => InitializeApplication()).ContinueWith(t => {// 初始化完成后切換到主界面Dispatcher.Invoke(() => SwitchToMainWindow());}, TaskScheduler.FromCurrentSynchronizationContext());}private void InitializeApplication(){// 更新狀態信息UpdateSplashStatus("正在加載配置...");Task.Delay(800).Wait();UpdateSplashStatus("正在初始化數據庫...");Task.Delay(1200).Wait();UpdateSplashStatus("正在準備界面...");Task.Delay(600).Wait();}private void UpdateSplashStatus(string message){Dispatcher.Invoke(() => {if (_splashScreen != null){_splashScreen.UpdateStatus(message);}});}private void SwitchToMainWindow(){// 創建主窗口var mainWindow = new MainWindow();// 關閉啟動窗口_splashScreen.Close();_splashScreen = null;// 顯示主窗口mainWindow.Show();}}
}
- 修改 App.xaml
<Application x:Class="YourNamespace.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Startup="Application_Startup"ShutdownMode="OnExplicitShutdown">
</Application>
優化建議
1. 添加淡入淡出效果
在切換窗口時添加平滑的動畫效果:
private void SwitchToMainWindow()
{// 創建主窗口但不立即顯示var mainWindow = new MainWindow();mainWindow.Opacity = 0;// 啟動窗口淡出var fadeOut = new DoubleAnimation(0, TimeSpan.FromSeconds(0.5));fadeOut.Completed += (s, e) => {_splashScreen.Close();_splashScreen = null;// 主窗口淡入mainWindow.Show();var fadeIn = new DoubleAnimation(1, TimeSpan.FromSeconds(0.5));mainWindow.BeginAnimation(Window.OpacityProperty, fadeIn);};_splashScreen.BeginAnimation(Window.OpacityProperty, fadeOut);
}
2. 處理 GIF 資源加載問題
確保 GIF 文件設置為資源:
- 在項目資源管理器中右鍵點擊 GIF 文件
- 選擇"屬性"
- 設置"生成操作"為"Resource"
3. 添加加載進度指示器
<Grid><!-- ... 其他元素 ... --><!-- 圓形進度條 --><ProgressBar x:Name="LoadingProgress" Value="0" Minimum="0" Maximum="100"Height="6" Width="300"HorizontalAlignment="Center" VerticalAlignment="Bottom"Margin="0,0,0,60"Foreground="#0EA5E9"><ProgressBar.Template><ControlTemplate TargetType="ProgressBar"><Grid><Border CornerRadius="3" Background="#3F3F46" BorderThickness="0" Height="6"/><Border CornerRadius="3" Background="#0EA5E9" BorderThickness="0" Height="6"HorizontalAlignment="Left"Width="{TemplateBinding Value}"/></Grid></ControlTemplate></ProgressBar.Template></ProgressBar>
</Grid>
在代碼中更新進度:
// 在 SplashScreen 中添加
public void UpdateProgress(int value)
{LoadingProgress.Value = value;
}// 在 App.xaml.cs 中
private void InitializeApplication()
{UpdateProgress(10);UpdateSplashStatus("正在加載配置...");Task.Delay(800).Wait();UpdateProgress(40);UpdateSplashStatus("正在初始化數據庫...");Task.Delay(1200).Wait();UpdateProgress(80);UpdateSplashStatus("正在準備界面...");Task.Delay(600).Wait();UpdateProgress(100);
}private void UpdateProgress(int value)
{Dispatcher.Invoke(() => {if (_splashScreen != null){_splashScreen.UpdateProgress(value);}});
}
常見問題解決方案
1. GIF 不顯示或不動
- 確保 GIF 文件路徑正確
- 檢查 GIF 文件屬性設置為"Resource"
- 嘗試使用完整資源路徑:
pack://application:,,,/YourAppName;component/Assets/loading.gif
- 確保 GIF 不是單幀圖像
2. 啟動界面位置不居中
- 設置
WindowStartupLocation="CenterScreen"
- 確保啟動窗口沒有設置
Left
和Top
屬性
3. 背景不透明
- 確保
AllowsTransparency="True"
- 設置
Background="Transparent"
- 移除窗口邊框:
WindowStyle="None"
4. 內存泄漏
- 在關閉窗口時停止動畫:
protected override void OnClosed(EventArgs e) {base.OnClosed(e);// 停止 GIF 動畫if (gifBehavior != null){ImageBehavior.SetAnimatedSource(LoadingGif, null);}// 清除資源LoadingGif.Source = null;LoadingGif = null; }
5. 多顯示器支持
public SplashScreen()
{InitializeComponent();// 在屏幕中心顯示var screen = System.Windows.Forms.Screen.PrimaryScreen;var screenWidth = screen.Bounds.Width;var screenHeight = screen.Bounds.Height;Left = (screenWidth - Width) / 2;Top = (screenHeight - Height) / 2;
}
總結
在 WPF 啟動界面中心加載 GIF 動畫可以通過以下步驟實現:
- 使用 WpfAnimatedGif 庫(推薦)或創建自定義 GIF 控件
- 設計透明無邊框的啟動窗口
- 將 GIF 放置在窗口中心
- 添加狀態文本和進度指示器
- 在 App 類中管理啟動窗口的生命周期
- 添加動畫效果提升用戶體驗
對于大多數項目,推薦使用 WpfAnimatedGif 庫,因為它簡單可靠且支持完整的 GIF 功能。如果你有特殊需求或不想添加外部依賴,可以使用自定義控件方法。
無論選擇哪種方法,都要注意資源管理和內存釋放,確保啟動窗口關閉后不會留下任何資源占用。