1. 程式人生 > 實用技巧 >WPF實現遊戲背景效果

WPF實現遊戲背景效果

前言

在使用一些應用的時候會發現等待介面做的使用者體驗很好,所以打算使用wpf實現一篇。

效果圖預覽

  1. 第一步需要一張無縫背景圖片(PS 圖片地址)。
  2. 準備飛機圖片。
  3. XAML程式碼。
     
    <Window.Resources>
            <ImageBrush x:Key="freeMachineImageBrush" ImageSource="/Images/飛機132x48.png"/>
        </Window.Resources>
    
    <Canvas Name="myCanvas" Focusable="True">
            <Rectangle Name="
    background" Height="400" Width="1262"/> <Rectangle Name="background2" Height="400" Width="1262" Canvas.Left="1262" /> <Rectangle Fill="{StaticResource freeMachineImageBrush}" Height="48" Width="128" Canvas.Left="336"/> </Canvas>

  4. 後臺程式碼。
    //建立定時器
    DispatcherTimer timer = new
    DispatcherTimer(); //定義影象畫刷 ImageBrush backgroundBrush = new ImageBrush(); //構造 timer.Tick += Engine; timer.Interval = TimeSpan.FromMilliseconds(20); backgroundBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Images/timg.jpg")); background.Fill = backgroundBrush; background2.Fill = backgroundBrush;
    Start();
    private void Engine(object sender, EventArgs e) { var backgroundLeft = Canvas.GetLeft(background) - 3; var background2Left = Canvas.GetLeft(background2) - 3; Canvas.SetLeft(background, backgroundLeft); Canvas.SetLeft(background2, background2Left); if (backgroundLeft <= -1262) { timer.Stop(); Start(); } } private void Start() { Canvas.SetLeft(background, 0); Canvas.SetLeft(background2, 1262); timer.Start(); }