第一次看到win2d是在14年9月IT之家的一篇文章微软推Win8.1/WP8.1通用Win2D API,图形加速,根据文章的描述,win2d api使用C#获取Direct2D的GPU图形加速功能,对于想要在win8.1和wp8.1开发游戏的同学来说是期待已久了。但当时由于工作关系并没有去深入了解。直到最近闲暇下来,便把win2D的相关文档认真翻阅了一遍,使用win2d开发了一款像素鸟beta作为测试,呵呵,游戏虽小,但也五脏俱全了。
自从XNA停止更新,VS2013也不再集成XNA模版以后,WP游戏开发的开发者面临着艰难的选择,转身学习C++和DirectX还是投入Unity3D的怀抱?不管哪种选择都有不小的学习代价。win2d的出现,我相信想要在wp和win8.1开发游戏便有了更直接的选择,既可以使用熟悉的C#进行开发又能使用GPU加速,win2d还可以和xaml完美集成,不管是对silverlight还是xna的开发者来说,都很容易上手。
说了这么多,就让我们一起来认识一下神秘的win2d吧。
首先,使用VS2013建立一个通用应用程序(Win2d不适用于silverlight的wp8应用和WPF)。
从Nuget添加win2d,目前的版本是0.0.12:
我们需要在配置管理器把编译平台改为X86(如果在真机调试,则改为ARM):
打开MainPage.xaml,添加对win2d命名空间的引用: xmlns:canvas="using:Microsoft.Graphics.Canvas"
在页面布局中添加CanvasControl:
<Page x:Class="App1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:App1" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:canvas="using:Microsoft.Graphics.Canvas" mc:Ignorable="d"> <Grid Name="grid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <canvas:CanvasControl Name="canvas"/> </Grid> </Page>
打开MainPage.xaml.cs文件:
在构造方法中注册CanvasControl的Draw事件:
public MainPage() { this.InitializeComponent(); canvas.Draw += canvas_Draw; } void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { }
在canvas_Draw方法中添加以下代码:
void canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { CanvasDrawingSession ds = args.DrawingSession; ds.DrawText("Hello Win2D", 240, 180, Colors.White); }
附录:
1,微软win2D团队博客:Win2D Team Blog
2,api文档:Win2D Documentation
3,Win2D源码可以在Github下载:https://github.com/Microsoft/Win2D