[Win2D] [translation] Win2D Quick Start and win2d Quick Start
Link: http://microsoft.github.io/Win2D/html/QuickStart.htm
Quick Start
This is a quick start tutorial for Win2D. We will introduce the basic functions of Win2D. You will learn in this tutorial:
• Add a Win2D project to the C # XAML Project
• Draw text and ry
• Apply filter effects
• Animation of Win2D content
• Optimal Implementation Based on Win2D
Install Visual Studio
• If you have not installed the supported Visual Studio version, follow these steps: Quick Start.
Create a new project with Win2D
1. Run Visual Studio and create a new project: file → new → project.
2. If your target is Windows 10, select: Installed → template → Visual C # → Windows → General → blank application (General Windows ).
If your target is Windows 8.1 and Visual Studio 2015 is used, select: Installed → template → Visual C # → Windows 8 → General → blank application (Universal Windows 8.1 ).
If your target is Windows 8.1 and Visual Studio 2013 is used, select: Installed → template → Visual C # → Windows 8.1 → blank application.
3. Enter the project name, select the Project Storage path, and click OK to create the project.
4. Currently, Win2D is released as an nuget package. You need to install it to use it. There are two packages, one for Windows 10 and the other for Windows 8.1. Select Tools> Nuget Package Manager> Manage Nuget packages of the solution.
5. Search for Win2D and select the corresponding package.
If the target is Windows 10, select Win2D. uwp.
If the target is Windows 8.1, select Win2D. win81.
Finally, click Install.
Add CanvasControl of Win2D to your App's Xaml File
1. To use Win2D, you need a place to draw your image. In the Xaml App, the simplest way is to add a CanvasControl to your Xaml page.
Before that, make sure that the solution platform of your project is x86 or x64, rather than Any CPU. Because Win2D is implemented based on C ++, you must specify a solution platform for any project that uses Win2D.
2. In Solution Explorer, double-click MainPage. xaml to open this page.
3. Before using CanvasControl, you must tell Xaml where the control is defined. In the page definition, add the following sentence:
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
Then your Xaml should be like this:
<Page ... xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml" mc:Ignorable="d">
4. Now, add the canvas: CanvasControl to the Grid element and give it a name. Here we call it "canvas ". Now your Xaml should be like this:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <canvas:CanvasControl x:Name="canvas"/></Grid>
5. Next, define the Draw event. CnavasControl calls the Draw event when you need to Draw or redraw the image.
<canvas:CanvasControl x:Name="canvas" Draw="canvas_Draw" />
Use Win2D to draw your first text
1. Open MainPage. xaml. cs in Solution Explorer.
2. Add the following namespace reference at the top of the C # file:
using Windows.UI;using System.Numerics;using Microsoft.Graphics.Canvas;using Microsoft.Graphics.Canvas.Effects;
3. Make sure the canvas_Draw method is added:
private void canvas_Draw( Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args){}
4. The CanvasDrawEventArgs parameter has a member called DrawingSession and the type is CanvasDrawingSession. This type provides a vast majority of drawing functions in Win2D. It has a bunch of methods named CanvasDrawingSession. DrawXXX, such as CanvasDrawingSession. DrawRectangle, CanvasDrawingSession. DrawImage, and CanvasDrawingSession. DrawText.
Add this line of code to the canvas_Draw method:
args.DrawingSession.DrawText("Hello, World!", 100, 100, Colors.Black);
The first parameter is "Hello, World! "Is the string you want to display in Win2D. The next two 100 means the distance from the left and top of the container under 100 DIPs. The last parameter is the color of the text.
5. Now you can run your App. Press F5 to compile and run. You should be able to see a blank window with black Hello, World! .
Correctly release resources used by Win2D
1. Before you plan to continue to draw other content, you should first add some code to avoid Memory leakage. The following steps are required for most Win2D programs written in. Net and controls in Win2D (for example, CanvasControl. Strictly speaking, the above Hello World will not affect, but it is a good habit to follow the regular rules.
For more information about memory leakage, click this link: http://microsoft.github.io/Win2D/html/RefCycles.htm
2. Open MainPage. xaml and find the Page element that contains your CanvasControl.
3. subscribe to the Unloaded event in the Page element. The Xaml code becomes like this:
<Page ... xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml" mc:Ignorable="d" Unloaded="Page_Unloaded">
4. Go to the MainPage. xaml. cs file and add the following code in Page_Unloaded:
void Page_Unloaded(object sender, RoutedEventArgs e){ this.canvas.RemoveFromVisualTree(); this.canvas = null;}
5. If your App contains multiple Win2D controls, repeat the preceding steps for each Win2D control. Because your App only has such a CanvasControl, the memory has been released now.
Draw some images
1. It is very easy to add 2D ry in your App. Add the following code at the end of the canvas_Draw method:
args.DrawingSession.DrawCircle(125, 125, 100, Colors.Green);args.DrawingSession.DrawLine(0, 0, 50, 200, Colors.Red);
The parameters of these two methods are similar to those of the DrawText method. The first line draws a circle with a center point (125,125), a radius of 100, and a circular color of green. The second line draws a red line from (50,200).
2. Press F5 to compile and run the program. You should see Hello, World! There is a green edge circle and a red line nearby.
You may want to know how to use more advanced painting methods, such as the width and style of the control line, or use a brush to fill the pattern. Win2D provides all the options for you to implement what you think. All DrawXXX methods provide multiple overloading to accept additional parameters, such as CanvasTextFormat (font, text size, and so on) parameters and CanvasStrokeStyle (vertex, line start and end, etc) type parameter.
You can view the API to learn about these parameters.
Dynamically generate drawing parameters
1. Now, we add a few changes to draw random color graphics and text.
Add the following code to MainPage. xaml. cs. This will help you generate random values during painting.
Random rnd = new Random();private Vector2 RndPosition(){ double x = rnd.NextDouble() * 500f; double y = rnd.NextDouble() * 500f; return new Vector2((float)x, (float)y);}private float RndRadius(){ return (float)rnd.NextDouble() * 150f;}private byte RndByte(){ return (byte)rnd.Next(256);}
2. modify the code in the canvas_Draw method and use random parameters.
private void canvas_Draw( Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args){ args.DrawingSession.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); args.DrawingSession.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); args.DrawingSession.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte()));}
Let's pause and see how the DrawText method has changed. The first parameter "Hello, World !" Is the same as before. The x and y positions are changed to a Vector2 object generated by RndPosition. Finally, use the Color. FromArgb method and pass A, R, G, and B to define A Color. A is the value of the Alpha channel, that is, the opacity of the color. In this example, we always use completely opaque, that is, 255.
The operations of DrawCircle and DrawLine are similar to DrawText, which is not detailed here.
3. Finally, pack it with a loop. Canvas_Draw should end with the code:
for (int i = 0; i < 100; i++){ args.DrawingSession.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); args.DrawingSession.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); args.DrawingSession.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte()));}
4. Run the program again. You should see a lot of text, lines, and circles with random positions and sizes.
Apply Image effects to content
1. image effects, also known as filter effects, are pixel-level graphical transformations. Saturation, blurred colors, and Gaussian Blur are common image effects. Image effects can be connected and applied together to achieve complex visual effects at minimal cost.
You can create a special effect (such as GaussianBlurEffect) and set its attributes (such as BlurAmount) by providing a source image (your initial content ), call the DrawImage method to draw the image processed by the special effect.
If you want to apply image effects to text and graphics, You need to first present the content to a CanvasCommandList object. This object can be used as a result input.
2. The code for modifying the canvas_Draw method is as follows:
CanvasCommandList cl = new CanvasCommandList(sender);using (CanvasDrawingSession clds = cl.CreateDrawingSession()){ for (int i = 0; i < 100; i++) { clds.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); }}
Just like how you get a CanvasDrawingSession from the CanvasDrawEventArgs object, you can also get a CanvasDrawingSession object from the CanvasCommandList. The only difference is that you just add the drawing command to the drawing task, instead of rendering it directly to CanvasControl. On the other hand, the command list is an intermediate object that stores rendering commands and is provided for actual rendering.
You may be aware that we use using to encapsulate the drawing command. DrawingSession is an object that implements the IDisposable interface and must be released when the painting is complete. Note: The CanvasDrawingSession obtained from CanvasDrawEventArgs is automatically released, and you do not need to manually release it. However, you must manually release your own CanvasDrawingSession.
3. Define GaussianBlurEffect and add the following code to the end of the canvas_Draw method.
GaussianBlurEffect blur = new GaussianBlurEffect();blur.Source = cl;blur.BlurAmount = 10.0f;args.DrawingSession.DrawImage(blur);
This Code creates a Gaussian blur, sets the source to the CanvasCommandList object just drawn, sets the Blur radius to 10, and then submits it to the original DrawingSession for rendering and output.
4. Run the program again and you will see that your straight lines, text, and circles are blurred.
Use CanvasAnimatedControl to fill your App with animations
1. Win2D allows you to update content or apply animation effects in real time at runtime. For example, each frame changes the Gaussian Blur radius. To implement this function, you need to use CanvasAnimatedControl.
CanvasControl is applicable to static content. It only triggers the Draw event when update or re-painting is required. If your content is constantly changing, you should use CanvasAnimatedControl. The use of these two controls is quite similar, except that CanvasAnimatedControl regularly triggers the Draw event. Generally, 60 Draw events are triggered every second.
2. Now we start to convert to CanvasAnimatedControl, go to MainPage. xaml, delete the previous code, and modify it as follows:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <canvas:CanvasAnimatedControl x:Name="canvas" Draw="canvas_DrawAnimated" CreateResources="canvas_CreateResources"/></Grid>
Similar to CanvasControl, you can subscribe to a Draw event (the method is canvas_DrawAnimated ). In addition, you should subscribe to an event named CreateResources.
Now, your program will be rendered 60 frames per second. For resources that only need to be created once and can be reused at each frame, we should do our best to optimize it, instead of creating it at each frame. The CreateResources event is triggered only when Win2D deems it necessary to re-create the resource, for example, when loading the page.
3. Return to MainPage. xaml. cs. Your previous code should be like this:
private void canvas_Draw( Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args){ CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { for (int i = 0; i < 100; i++) { clds.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); } } GaussianBlurEffect blur = new GaussianBlurEffect(); blur.Source = cl; blur.BlurAmount = 10.0f; args.DrawingSession.DrawImage(blur);}
Currently, most of the Code in this section does not need to be executed on every frame. The command list for drawing text, straight lines, and circles remains unchanged. what needs to be changed is the Gaussian Blur radius, therefore, we will move the "static" part of the code to the CreateResources method.
Use Ctrl + X to cut out the Code except the last line (args. DrawingSession. DrawImage (blur. You can delete the canvas_Draw method, because CanvasAnimatedControl uses the canvas_AnimatedDraw method.
4. Find the canvas_CreateResources method:
private void canvas_CreateResources( Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args){}
Press Ctrl + V to paste the previously cut code. Next, place the definition of GaussianBlurEffect outside the method body to become a member of the MainPage class. Now, your code should be like this:
GaussianBlurEffect blur;private void canvas_CreateResources( Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args){ CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { for (int i = 0; i < 100; i++) { clds.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); } } blur = new GaussianBlurEffect() { Source = cl, BlurAmount = 10.0f };}
5. Now, you can animated Gaussian blur, find the canvas_AnimatedDraw method, and then add the following code:
private void canvas_AnimatedDraw( Microsoft.Graphics.Canvas.UI.Xaml.ICanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedDrawEventArgs args){ float radius = (float)(1 + Math.Sin(args.Timing.TotalTime.TotalSeconds)) * 10f; blur.BlurAmount = radius; args.DrawingSession.DrawImage(blur);}
Here, the running time is read from the CanvasAnimatedDrawEventArgs parameter and the radius of Gaussian Blur is calculated. The sine function is used to show the effect of a time period change. Finally, it is presented by GaussianBlurEffect.
6. Run the program and you will see that the Blur degree of the content also changes over time.
Congratulations! You have completed this quick start tutorial! I hope you already know how to create a rich and vivid view with just a few lines of code.
PS: This article is a scum translation. If you do not like it, Do not spray it. If you are helpful, please click it. Thank you!