與眾不同 windows phone (1) - Hello Windows Phone
作者:webabcd
介紹
與眾不同 windows phone 7.5 (sdk 7.1)
- 使用 Silverlight 開發 Windows Phone 應用程序
- 使用 XNA 開發 Windows Phone 應用程序
- 使用 Silverlight 和 XNA 組合開發 Windows Phone 應用程序(在 Silverlight 中融入 XNA)
示例
1、使用 Silverlight 開發 Windows Phone App 的 Demo
MainPage.xaml
<phone:PhoneApplicationPage x:Class="Silverlight.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <StackPanel> <!--按鈕--> <Button Name="btn" Content="hello webabcd" /> </StackPanel> </phone:PhoneApplicationPage>
MainPage.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; namespace Silverlight { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { // 彈出 MessageBox 信息 btn.Click += delegate { MessageBox.Show("hello webabcd"); }; } } }
2、使用 XNA 開發 Windows Phone App 的 Demo
Game1.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; namespace XNA { // 啟動時先 Initialize,再 LoadContent,退出時 UnloadContent public class Game1 : Microsoft.Xna.Framework.Game { // 圖形設備(顯卡)管理器,XNA 在游戲窗口上做的所有事情都要通過此對象 GraphicsDeviceManager graphics; // 精靈繪制器 SpriteBatch spriteBatch; // 2D 紋理對象 Texture2D sprite; public Game1() { graphics = new GraphicsDeviceManager(this); // 指定游戲窗口的寬和高,不設置的話會花屏 graphics.PreferredBackBufferWidth = this.Window.ClientBounds.Width; graphics.PreferredBackBufferHeight = this.Window.ClientBounds.Height; Content.RootDirectory = "Content"; // 兩次繪制的間隔時間,本例為每 1/30 秒繪制一次,即幀率為 30 fps。此屬性默認值為 60 fps TargetElapsedTime = TimeSpan.FromSeconds(1f / 30); // 當禁止在鎖屏狀態下運行應用程序空閑檢測(默認是開啟的)時,將此屬性設置為 1 秒鍾,可減少鎖屏啟動應用程序時的耗電量。此屬性默認值為 0.02 秒 InactiveSleepTime = TimeSpan.FromSeconds(1); } /// <summary> /// 游戲運行前的一些初始化工作 /// </summary> protected override void Initialize() { base.Initialize(); } /// <summary> /// 加載游戲所需用到的資源,如圖像和音效等 /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); // 將圖片 Image/Son 加載到 Texture2D 對象中 sprite = Content.Load<Texture2D>("Image/Son"); } /// <summary> /// 手工釋放對象,游戲退出時會自動調用此方法 /// 注:XNA 會自動進行垃圾回收 /// </summary> protected override void UnloadContent() { } /// <summary> /// Draw 之前的邏輯計算 /// </summary> /// <param name="gameTime">游戲的當前時間對象</param> protected override void Update(GameTime gameTime) { // 用戶按返回鍵則退出應用程序 if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); base.Update(gameTime); } /// <summary> /// 在游戲窗口上進行繪制 /// </summary> /// <param name="gameTime">游戲的當前時間對象</param> protected override void Draw(GameTime gameTime) { // 清除游戲窗口上的所有對象,然后以 CornflowerBlue 顏色作為背景 GraphicsDevice.Clear(Color.CornflowerBlue); // SpriteBatch.Draw() - 用於繪制圖像,其應在 SpriteBatch.Begin() 和 SpriteBatch.End() 之間調用 spriteBatch.Begin(); spriteBatch.Draw(sprite, new Vector2((this.Window.ClientBounds.Width - sprite.Width) / 2, (this.Window.ClientBounds.Height - sprite.Height) / 2), Color.White); spriteBatch.End(); base.Draw(gameTime); } } }
3、使用 Silverlight 和 XNA 組合開發 Windows Phone App 的 Demo(在 Silverlight 中融入 XNA)
GamePage.xaml
<phone:PhoneApplicationPage x:Class="Combine.GamePage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="480" shell:SystemTray.IsVisible="False"> <StackPanel Orientation="Vertical"> <!-- 4 個按鈕,用於控制 sprite 的 上/下/左/右 移動 --> <Button Name="btnUp" Content="上" Click="btnUp_Click" /> <Button Name="btnDown" Content="下" Click="btnDown_Click" /> <Button Name="btnLeft" Content="左" Click="btnLeft_Click" /> <Button Name="btnRight" Content="右" Click="btnRight_Click" /> </StackPanel> </phone:PhoneApplicationPage>
AppServiceProvider.cs
using System; using System.Collections.Generic; namespace Combine { /// <summary> /// Implements IServiceProvider for the application. This type is exposed through the App.Services /// property and can be used for ContentManagers or other types that need access to an IServiceProvider. /// </summary> public class AppServiceProvider : IServiceProvider { // A map of service type to the services themselves private readonly Dictionary<Type, object> services = new Dictionary<Type, object>(); /// <summary> /// Adds a new service to the service provider. /// </summary> /// <param name="serviceType">The type of service to add.</param> /// <param name="service">The service object itself.</param> public void AddService(Type serviceType, object service) { // Validate the input if (serviceType == null) throw new ArgumentNullException("serviceType"); if (service == null) throw new ArgumentNullException("service"); if (!serviceType.IsAssignableFrom(service.GetType())) throw new ArgumentException("service does not match the specified serviceType"); // Add the service to the dictionary services.Add(serviceType, service); } /// <summary> /// Gets a service from the service provider. /// </summary> /// <param name="serviceType">The type of service to retrieve.</param> /// <returns>The service object registered for the specified type..</returns> public object GetService(Type serviceType) { // Validate the input if (serviceType == null) throw new ArgumentNullException("serviceType"); // Retrieve the service from the dictionary return services[serviceType]; } /// <summary> /// Removes a service from the service provider. /// </summary> /// <param name="serviceType">The type of service to remove.</param> public void RemoveService(Type serviceType) { // Validate the input if (serviceType == null) throw new ArgumentNullException("serviceType"); // Remove the service from the dictionary services.Remove(serviceType); } } }
GamePage.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Combine { public partial class GamePage : PhoneApplicationPage { // 以 XNA 的方式加載資源 ContentManager contentManager; // 計時器 GameTimer timer; // 精靈繪制器 SpriteBatch spriteBatch; // 2D 紋理對象 Texture2D sprite; // silverlight 元素繪制器 UIElementRenderer elementRenderer; // sprite 的位置信息 Vector2 position = Vector2.Zero; public GamePage() { InitializeComponent(); // 獲取 ContentManager 對象 contentManager = (Application.Current as App).Content; // 指定計時器每 1/30 秒執行一次,即幀率為 30 fps timer = new GameTimer(); timer.UpdateInterval = TimeSpan.FromTicks(333333); timer.Update += OnUpdate; timer.Draw += OnDraw; // 當 silverlight 可視樹發生改變時 LayoutUpdated += new EventHandler(GamePage_LayoutUpdated); } protected override void OnNavigatedTo(NavigationEventArgs e) { // 指示顯示設備需要同時支持 silverlight 和 XNA SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true); // 實例化精靈繪制器 spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice); // 將圖片 Image/Son 加載到 Texture2D 對象中 if (sprite == null) { sprite = contentManager.Load<Texture2D>("Image/Son"); } // 啟動計時器 timer.Start(); base.OnNavigatedTo(e); } void GamePage_LayoutUpdated(object sender, EventArgs e) { // 指定窗口的寬和高 if ((ActualWidth > 0) && (ActualHeight > 0)) { SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = (int)ActualWidth; SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = (int)ActualHeight; } // 實例化 silverlight 元素繪制器 if (elementRenderer == null) { elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight); } } protected override void OnNavigatedFrom(NavigationEventArgs e) { // 停止計時器 timer.Stop(); // 指示顯示設備關閉對 XNA 的支持 SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false); base.OnNavigatedFrom(e); } /// <summary> /// Draw 之前的邏輯計算 /// </summary> private void OnUpdate(object sender, GameTimerEventArgs e) { } /// <summary> /// 在窗口上進行繪制 /// </summary> private void OnDraw(object sender, GameTimerEventArgs e) { // 清除窗口上的所有對象,然后以 CornflowerBlue 顏色作為背景 SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black); // 呈現 silverlight 元素到緩沖區 elementRenderer.Render(); spriteBatch.Begin(); // 繪制 silverlight 元素 spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White); // 繪制 sprite 對象 spriteBatch.Draw(sprite, position, Color.White); spriteBatch.End(); } private void btnUp_Click(object sender, RoutedEventArgs e) { position.Y--; } private void btnDown_Click(object sender, RoutedEventArgs e) { position.Y++; } private void btnLeft_Click(object sender, RoutedEventArgs e) { position.X--; } private void btnRight_Click(object sender, RoutedEventArgs e) { position.X++; } } }
OK
[源碼下載]