### Basic XAML Drawing Control Setup
Source: https://context7.com/microsoft/win2d/llms.txt
Set up the CanvasControl in XAML, defining its name, event handlers for resource creation and drawing, and a default clear color.
```xml
```
--------------------------------
### Check CanvasDevice Capabilities
Source: https://context7.com/microsoft/win2d/llms.txt
Provides examples of checking various capabilities of a CanvasDevice, such as pixel format support, buffer precision, maximum bitmap size, and whether the device is currently lost.
```csharp
// Check device capabilities
void CheckDeviceCapabilities(CanvasDevice device)
{
// Check pixel format support
bool supportsR16G16 = device.IsPixelFormatSupported(
DirectXPixelFormat.R16G16Float);
// Check buffer precision support
bool supports16BitFloat = device.IsBufferPrecisionSupported(
CanvasBufferPrecision.Precision16Float);
// Get maximum bitmap size
int maxBitmapSize = device.MaximumBitmapSizeInPixels;
// Check if device is lost
bool isLost = device.IsDeviceLost(0);
Debug.WriteLine($"Max bitmap size: {maxBitmapSize}");
Debug.WriteLine($"Supports R16G16 float: {supportsR16G16}");
}
```
--------------------------------
### XAML Setup for Win2D CanvasControl
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/README.md
This XAML snippet shows how to declare a CanvasControl within a Grid layout. Ensure the correct namespace is included. The Draw event handler is specified.
```xml
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
```
--------------------------------
### Basic Sample Export
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/tools/exportsample/README.txt
Use this command to export Win2D samples to a specified directory. Ensure you replace 'C:\Path\To\Win2D' and 'C:\Path\To\Samples' with your actual paths.
```batch
C:\Path\To\Win2D> exportsample c:\Path\To\Samples
```
--------------------------------
### Create CanvasDevice Instances
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates various ways to create CanvasDevice instances, including shared devices, dedicated devices, and forcing software rendering. Use GetSharedDevice for multiple controls.
```csharp
// Device creation
void CreateDevices()
{
// Get shared device (recommended for multiple controls)
var sharedDevice = CanvasDevice.GetSharedDevice();
// Create dedicated device
var dedicatedDevice = new CanvasDevice();
// Force software rendering
var softwareDevice = new CanvasDevice(true);
// Get shared device with specific options
var forceSoftware = CanvasDevice.GetSharedDevice(forceSoftwareRenderer: false);
}
```
--------------------------------
### Create and Use Win2D Brushes
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates creating and using solid color, linear gradient, radial gradient, and image brushes. Brush properties can be modified dynamically.
```csharp
using Microsoft.Graphics.Canvas.Brushes;
CanvasSolidColorBrush solidBrush;
CanvasLinearGradientBrush linearGradient;
CanvasRadialGradientBrush radialGradient;
CanvasImageBrush imageBrush;
void CreateBrushes(ICanvasResourceCreator creator, CanvasBitmap texture)
{
// Solid color brush
solidBrush = new CanvasSolidColorBrush(creator, Colors.Purple);
// Linear gradient brush
var linearStops = new CanvasGradientStop[]
{
new CanvasGradientStop { Position = 0.0f, Color = Colors.Red },
new CanvasGradientStop { Position = 0.5f, Color = Colors.Green },
new CanvasGradientStop { Position = 1.0f, Color = Colors.Blue }
};
linearGradient = new CanvasLinearGradientBrush(creator, linearStops);
linearGradient.StartPoint = new Vector2(0, 0);
linearGradient.EndPoint = new Vector2(200, 200);
// Radial gradient brush
var radialStops = new CanvasGradientStop[]
{
new CanvasGradientStop { Position = 0.0f, Color = Colors.White },
new CanvasGradientStop { Position = 0.5f, Color = Colors.Yellow },
new CanvasGradientStop { Position = 1.0f, Color = Colors.Orange }
};
radialGradient = new CanvasRadialGradientBrush(creator, radialStops);
radialGradient.Center = new Vector2(100, 100);
radialGradient.RadiusX = 100;
radialGradient.RadiusY = 100;
// Image brush (tiled texture)
imageBrush = new CanvasImageBrush(creator, texture);
imageBrush.ExtendX = CanvasEdgeBehavior.Wrap;
imageBrush.ExtendY = CanvasEdgeBehavior.Wrap;
}
void DrawWithBrushes(CanvasDrawingSession ds)
{
// Use brushes for fills and strokes
ds.FillRectangle(0, 0, 200, 200, solidBrush);
ds.FillEllipse(350, 100, 100, 100, linearGradient);
ds.FillRoundedRectangle(500, 0, 200, 200, 20, 20, radialGradient);
ds.FillRectangle(0, 250, 700, 200, imageBrush);
// Modify brush properties dynamically
solidBrush.Color = Colors.Cyan;
solidBrush.Opacity = 0.5f;
ds.FillCircle(100, 350, 80, solidBrush);
}
```
--------------------------------
### Sample Export with Custom NuGet Package Source
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/tools/exportsample/README.txt
Configure the export process to restore NuGet packages from a specific network share. Replace placeholders with your actual paths and network share details.
```batch
C:\Path\To\Win2D> exportsample c:\Path\To\Samples /PackageSource:\\networkshare\path\to\nuget\directory
```
--------------------------------
### Create Basic Image Effects in Win2D
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates the creation of common image effects like Gaussian blur, saturation adjustment, and 2D transformations. Ensure the source image is loaded before creating these effects.
```csharp
using Microsoft.Graphics.Canvas.Effects;
CanvasBitmap sourceImage;
GaussianBlurEffect blurEffect;
SaturationEffect saturationEffect;
Transform2DEffect transformEffect;
void CreateEffects()
{
// Simple Gaussian blur
blurEffect = new GaussianBlurEffect
{
Source = sourceImage,
BlurAmount = 5.0f,
BorderMode = EffectBorderMode.Soft
};
// Saturation adjustment
saturationEffect = new SaturationEffect
{
Source = sourceImage,
Saturation = 0.5f // 0 = grayscale, 1 = original, 2 = oversaturated
};
// Transform effect (scale, rotate, translate)
transformEffect = new Transform2DEffect
{
Source = sourceImage,
TransformMatrix = Matrix3x2.CreateRotation((float)Math.PI / 6) *
Matrix3x2.CreateScale(1.5f)
};
}
```
--------------------------------
### Chain Multiple Image Effects in Win2D
Source: https://context7.com/microsoft/win2d/llms.txt
Illustrates how to chain multiple image effects together to create a complex visual pipeline. Effects are applied sequentially, with the output of one effect serving as the input for the next.
```csharp
// Chain multiple effects
ICanvasImage CreateEffectChain(CanvasBitmap source)
{
// Apply contrast adjustment
var contrast = new ContrastEffect
{
Source = source,
Contrast = 0.5f
};
// Then apply vignette
var vignette = new VignetteEffect
{
Source = contrast,
Amount = 0.5f,
Curve = 0.5f,
Color = Colors.Black
};
// Finally apply slight blur
var blur = new GaussianBlurEffect
{
Source = vignette,
BlurAmount = 1.0f
};
return blur;
}
```
--------------------------------
### Draw with Opacity Layer
Source: https://context7.com/microsoft/win2d/llms.txt
Shows how to create a simple layer with a specified opacity. Drawing operations within this layer will be rendered with the given transparency.
```csharp
// Simple opacity layer
using (ds.CreateLayer(0.5f))
{
ds.FillRectangle(0, 0, 200, 200, Colors.Red);
ds.FillCircle(100, 100, 80, Colors.Blue);
}
```
--------------------------------
### Create and Draw Text Layout with Formatting
Source: https://context7.com/microsoft/win2d/llms.txt
Illustrates creating a CanvasTextLayout for advanced text control, applying formatting to specific text ranges, and performing hit testing. Requires an ICanvasResourceCreator.
```csharp
// Advanced text layout
void DrawTextLayout(CanvasDrawingSession ds, ICanvasResourceCreator creator)
{
var format = new CanvasTextFormat
{
FontSize = 20,
WordWrapping = CanvasWordWrapping.Wrap
};
string text = "Win2D provides powerful text rendering with full Unicode support, " +
"including complex scripts, ligatures, and OpenType features.";
// Create text layout for advanced control
var layout = new CanvasTextLayout(creator, text, format, 300, 200);
// Apply formatting to specific ranges
layout.SetFontSize(0, 5, 28); // "Win2D" larger
layout.SetFontWeight(0, 5, FontWeights.Bold);
layout.SetColor(0, 5, Colors.Yellow);
layout.SetFontStyle(50, 20, FontStyle.Italic);
layout.SetUnderline(70, 15, true);
// Draw the layout
ds.DrawTextLayout(layout, 50, 50, Colors.White);
// Get layout metrics
var metrics = layout.LayoutBounds;
ds.DrawRectangle(50, 50, (float)metrics.Width, (float)metrics.Height,
Colors.Gray, 1);
// Hit testing
var hitTestResult = layout.HitTest(100, 80);
if (hitTestResult.IsInside)
{
// Highlight character at hit position
var charBounds = layout.GetCharacterRegions(
hitTestResult.TextPosition, 1);
foreach (var region in charBounds)
{
ds.FillRectangle(region.LayoutBounds,
Color.FromArgb(64, 255, 255, 0));
}
}
}
```
--------------------------------
### Load Bitmaps Asynchronously
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates loading CanvasBitmaps from different sources like app packages, URIs, streams, and with specific alpha modes and DPI settings.
```csharp
// Load from app package
var bitmap1 = await CanvasBitmap.LoadAsync(sender, "Assets/image.png");
```
```csharp
// Load from URI
var bitmap2 = await CanvasBitmap.LoadAsync(sender,
new Uri("ms-appx:///Assets/photo.jpg"));
```
```csharp
// Load with specific DPI
var bitmap3 = await CanvasBitmap.LoadAsync(sender, "Assets/icon.png", 96.0f);
```
```csharp
// Load with alpha mode
var bitmap4 = await CanvasBitmap.LoadAsync(sender, "Assets/sprite.png",
96.0f, CanvasAlphaMode.Premultiplied);
```
```csharp
// Load from stream
var file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/data.png"));
using (var stream = await file.OpenReadAsync())
{
var bitmap5 = await CanvasBitmap.LoadAsync(sender, stream);
}
```
--------------------------------
### Create and Record CanvasCommandList
Source: https://context7.com/microsoft/win2d/llms.txt
Instantiate a CanvasCommandList and record drawing operations within its drawing session. This is useful for deferred rendering.
```csharp
CanvasCommandList commandList;
void CreateCommandList(ICanvasResourceCreator creator)
{
commandList = new CanvasCommandList(creator);
using (var ds = commandList.CreateDrawingSession())
{
// Record drawing commands
ds.Clear(Colors.Transparent);
ds.FillCircle(100, 100, 50, Colors.Red);
ds.FillCircle(150, 100, 50, Colors.Blue);
ds.DrawText("Command List", 50, 170, Colors.White);
}
}
```
--------------------------------
### Render Text Using Different Brushes
Source: https://context7.com/microsoft/win2d/llms.txt
Shows how to draw text using various brush types, including solid color, linear gradient, and radial gradient brushes. Ensure brushes are disposed of properly after use.
```csharp
// Using brushes for text
void DrawTextWithBrushes(CanvasDrawingSession ds, ICanvasResourceCreator creator)
{
var format = new CanvasTextFormat { FontSize = 48, FontWeight = FontWeights.Bold };
// Solid color brush
using (var solidBrush = new CanvasSolidColorBrush(creator, Colors.Red))
{
ds.DrawText("Solid Brush", 50, 50, solidBrush, format);
}
// Linear gradient brush
var stops = new CanvasGradientStop[]
{
new CanvasGradientStop { Position = 0, Color = Colors.Red },
new CanvasGradientStop { Position = 0.5f, Color = Colors.Yellow },
new CanvasGradientStop { Position = 1, Color = Colors.Blue }
};
using (var gradientBrush = new CanvasLinearGradientBrush(creator, stops))
{
gradientBrush.StartPoint = new Vector2(50, 150);
gradientBrush.EndPoint = new Vector2(400, 150);
ds.DrawText("Gradient Text", 50, 120, gradientBrush, format);
}
// Radial gradient brush
using (var radialBrush = new CanvasRadialGradientBrush(creator, stops))
{
radialBrush.Center = new Vector2(200, 220);
radialBrush.RadiusX = 150;
radialBrush.RadiusY = 50;
ds.DrawText("Radial Gradient", 50, 200, radialBrush, format);
}
}
```
--------------------------------
### Trim CanvasDevice Resources
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates how to trim device resources using the Trim() method. This should be called on application suspend to release unused GPU memory.
```csharp
// Trim device resources (call on app suspend)
void OnSuspending(CanvasDevice device)
{
device.Trim();
}
```
--------------------------------
### Draw Basic and Formatted Text with CanvasTextFormat
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates simple text drawing and text drawing with advanced formatting options using CanvasTextFormat. Ensure CanvasTextFormat properties are set before drawing.
```csharp
using Microsoft.Graphics.Canvas.Text;
void DrawText(CanvasDrawingSession ds)
{
// Simple text drawing
ds.DrawText("Hello World!", 100, 100, Colors.White);
// Text with format options
var format = new CanvasTextFormat
{
FontFamily = "Segoe UI",
FontSize = 32,
FontWeight = FontWeights.Bold,
FontStyle = FontStyle.Italic,
HorizontalAlignment = CanvasHorizontalAlignment.Center,
VerticalAlignment = CanvasVerticalAlignment.Center,
WordWrapping = CanvasWordWrapping.Wrap
};
ds.DrawText("Formatted Text", new Rect(0, 200, 400, 100), Colors.Yellow, format);
// Different font families
var fonts = new[] { "Arial", "Times New Roman", "Courier New", "Comic Sans MS" };
for (int i = 0; i < fonts.Length; i++)
{
var f = new CanvasTextFormat { FontFamily = fonts[i], FontSize = 24 };
ds.DrawText($"Font: {fonts[i]}", 50, 300 + i * 40, Colors.White, f);
}
}
```
--------------------------------
### Save Bitmaps Asynchronously
Source: https://context7.com/microsoft/win2d/llms.txt
Illustrates saving a CanvasBitmap to a file in PNG format or JPEG format with specified quality.
```csharp
// Save as PNG
await bitmap.SaveAsync(stream, CanvasBitmapFileFormat.Png);
```
```csharp
// Or save as JPEG with quality
// await bitmap.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg, 0.9f);
```
--------------------------------
### Draw with Clipping Layer (Geometry)
Source: https://context7.com/microsoft/win2d/llms.txt
Illustrates creating a layer that clips drawing operations to a specified CanvasGeometry. Only the parts of the drawing that fall within the geometry will be visible.
```csharp
// Clipping layer with geometry
var clipGeometry = CanvasGeometry.CreateCircle(creator, 400, 100, 80);
using (ds.CreateLayer(1.0f, clipGeometry))
{
// This drawing is clipped to the circle
ds.FillRectangle(300, 0, 200, 200, Colors.Green);
ds.DrawText("Clipped!", 350, 90, Colors.White);
}
```
--------------------------------
### Draw with Brush Mask Layer
Source: https://context7.com/microsoft/win2d/llms.txt
Shows how to use a brush, specifically a linear gradient brush, as a mask for a layer's opacity. This allows for gradient-based transparency effects.
```csharp
// Layer with brush mask (gradient opacity)
var stops = new CanvasGradientStop[]
{
new CanvasGradientStop { Position = 0, Color = Color.FromArgb(255, 0, 0, 0) },
new CanvasGradientStop { Position = 1, Color = Color.FromArgb(0, 0, 0, 0) }
};
using (var maskBrush = new CanvasLinearGradientBrush(creator, stops))
{
maskBrush.StartPoint = new Vector2(300, 250);
maskBrush.EndPoint = new Vector2(500, 250);
using (ds.CreateLayer(maskBrush))
{
ds.FillRectangle(300, 250, 200, 150, Colors.Orange);
}
}
```
--------------------------------
### Combine Geometries using Boolean Operations
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates combining two circles using Union, Intersection, Exclude, and XOR operations. Requires a CanvasDrawingSession and an ICanvasResourceCreator.
```csharp
// Combine geometries
void CombineGeometries(CanvasDrawingSession ds, ICanvasResourceCreator creator)
{
var circle1 = CanvasGeometry.CreateCircle(creator, 100, 100, 60);
var circle2 = CanvasGeometry.CreateCircle(creator, 150, 100, 60);
// Union
var union = circle1.CombineWith(circle2, Matrix3x2.Identity,
CanvasGeometryCombine.Union);
ds.FillGeometry(union, 0, 0, Colors.Blue);
// Intersection
var intersect = circle1.CombineWith(circle2, Matrix3x2.Identity,
CanvasGeometryCombine.Intersect);
ds.FillGeometry(intersect, 200, 0, Colors.Green);
// Exclude
var exclude = circle1.CombineWith(circle2, Matrix3x2.Identity,
CanvasGeometryCombine.Exclude);
ds.FillGeometry(exclude, 400, 0, Colors.Red);
// XOR
var xor = circle1.CombineWith(circle2, Matrix3x2.Identity,
CanvasGeometryCombine.Xor);
ds.FillGeometry(xor, 0, 200, Colors.Purple);
}
```
--------------------------------
### Draw with Clipping Layer (Rectangle)
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates creating a layer that clips drawing operations to a specified Rect. Content outside this rectangle will not be rendered.
```csharp
// Layer with rectangle clip
using (ds.CreateLayer(0.8f, new Rect(50, 250, 200, 150)))
{
ds.FillRectangle(0, 200, 300, 250, Colors.Purple);
}
```
--------------------------------
### Create Bitmaps from Pixel Data
Source: https://context7.com/microsoft/win2d/llms.txt
Shows how to create CanvasBitmaps programmatically from arrays of Color objects or byte arrays representing pixel data in BGRA format.
```csharp
// Create from Color array
Color[] pixels = new Color[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Create gradient pattern
pixels[y * width + x] = Color.FromArgb(255,
(byte)(x * 255 / width),
(byte)(y * 255 / height),
128);
}
}
var colorBitmap = CanvasBitmap.CreateFromColors(sender, pixels, width, height);
```
```csharp
// Create from byte array (BGRA format)
byte[] bytes = new byte[width * height * 4];
for (int i = 0; i < bytes.Length; i += 4)
{
bytes[i] = 255; // Blue
bytes[i + 1] = 128; // Green
bytes[i + 2] = 64; // Red
bytes[i + 3] = 255; // Alpha
}
var byteBitmap = CanvasBitmap.CreateFromBytes(sender, bytes, width, height,
DirectXPixelFormat.B8G8R8A8UIntNormalized);
```
--------------------------------
### Implement Game Loop Logic with CanvasAnimatedControl
Source: https://context7.com/microsoft/win2d/llms.txt
C# code for handling game logic updates and drawing within a CanvasAnimatedControl. Includes ball movement, bouncing, and FPS display.
```csharp
using System.Numerics;
public sealed partial class GamePage : Page
{
Vector2 ballPosition = new Vector2(100, 100);
Vector2 ballVelocity = new Vector2(300, 200);
const float ballRadius = 20;
void AnimatedCanvas_CreateResources(CanvasAnimatedControl sender,
CanvasCreateResourcesEventArgs args)
{
// Initialize game resources here
}
void AnimatedCanvas_Update(ICanvasAnimatedControl sender,
CanvasAnimatedUpdateEventArgs args)
{
// Update game logic - called at fixed intervals (60 FPS by default)
float dt = (float)args.Timing.ElapsedTime.TotalSeconds;
// Move ball
ballPosition += ballVelocity * dt;
// Bounce off walls
var size = sender.Size;
if (ballPosition.X - ballRadius < 0 || ballPosition.X + ballRadius > size.Width)
ballVelocity.X = -ballVelocity.X;
if (ballPosition.Y - ballRadius < 0 || ballPosition.Y + ballRadius > size.Height)
ballVelocity.Y = -ballVelocity.Y;
// Clamp position
ballPosition.X = Math.Clamp(ballPosition.X, ballRadius, (float)size.Width - ballRadius);
ballPosition.Y = Math.Clamp(ballPosition.Y, ballRadius, (float)size.Height - ballRadius);
}
void AnimatedCanvas_Draw(ICanvasAnimatedControl sender,
CanvasAnimatedDrawEventArgs args)
{
var ds = args.DrawingSession;
// Draw the ball
ds.FillCircle(ballPosition, ballRadius, Colors.Red);
ds.DrawCircle(ballPosition, ballRadius, Colors.White, 2);
// Show FPS
ds.DrawText($
```
```csharp
FPS: {1.0 / args.Timing.ElapsedTime.TotalSeconds:F1}",
10, 10, Colors.Yellow);
}
}
```
--------------------------------
### Handle CanvasDevice Lost Events
Source: https://context7.com/microsoft/win2d/llms.txt
Sets up an event handler for the DeviceLost event on a CanvasDevice. This is crucial for recreating resources when the GPU device is lost and needs to be re-initialized.
```csharp
// Device lost handling
void SetupDeviceLostHandling(CanvasDevice device)
{
device.DeviceLost += (sender, args) =>
{
// Device was lost, need to recreate resources
Debug.WriteLine($"Device lost! Reason: {args.Message}");
// Recreate the device
var newDevice = CanvasDevice.GetSharedDevice();
// Recreate all resources on the new device
RecreateResources(newDevice);
};
}
```
--------------------------------
### Draw Bitmaps
Source: https://context7.com/microsoft/win2d/llms.txt
Demonstrates various ways to draw a CanvasBitmap onto a CanvasDrawingSession, including different positions, scaling, source rectangles, opacity, and interpolation modes.
```csharp
// Draw at position
ds.DrawImage(bitmap, 0, 0);
ds.DrawImage(bitmap, new Vector2(100, 100));
```
```csharp
// Draw scaled to destination rectangle
ds.DrawImage(bitmap, new Rect(200, 0, 150, 100));
```
```csharp
// Draw with source rectangle (sprite sheet)
ds.DrawImage(bitmap, new Vector2(0, 200),
new Rect(0, 0, 32, 32)); // Source rect
```
```csharp
// Draw with opacity
ds.DrawImage(bitmap, new Vector2(100, 200),
bitmap.Bounds, 0.5f); // 50% opacity
```
```csharp
// Draw with interpolation mode
ds.DrawImage(bitmap, new Rect(200, 200, 200, 200), bitmap.Bounds,
1.0f, CanvasImageInterpolation.NearestNeighbor);
```
--------------------------------
### Create a Curved Path with Bezier and Arc
Source: https://context7.com/microsoft/win2d/llms.txt
Constructs a path with quadratic and cubic Bezier curves, as well as an arc segment, using CanvasPathBuilder. The path is left open.
```csharp
// Create path with curves
CanvasGeometry CreateCurvedPath(ICanvasResourceCreator creator)
{
var pathBuilder = new CanvasPathBuilder(creator);
pathBuilder.BeginFigure(0, 100);
// Quadratic bezier curve
pathBuilder.AddQuadraticBezier(
new Vector2(50, 0), // Control point
new Vector2(100, 100) // End point
);
// Cubic bezier curve
pathBuilder.AddCubicBezier(
new Vector2(150, 0), // Control point 1
new Vector2(200, 200), // Control point 2
new Vector2(250, 100) // End point
);
// Arc
pathBuilder.AddArc(
new Vector2(350, 100), // End point
50, 50, // Radius X, Y
0, // Rotation angle
CanvasSweepDirection.Clockwise,
CanvasArcSize.Small
);
pathBuilder.EndFigure(CanvasFigureLoop.Open);
return CanvasGeometry.CreatePath(pathBuilder);
}
```
--------------------------------
### Perform Geometry Operations
Source: https://context7.com/microsoft/win2d/llms.txt
Illustrates various geometry operations including stroking, simplifying, transforming, computing bounds and area, and hit testing. Requires an ICanvasResourceCreator.
```csharp
// Geometry operations
void GeometryOperations(ICanvasResourceCreator creator)
{
var geometry = CanvasGeometry.CreateRectangle(creator, 0, 0, 100, 100);
// Get stroked outline
var stroked = geometry.Stroke(10);
// Simplify to lines only
var simplified = geometry.Simplify(CanvasGeometrySimplification.Lines);
// Transform geometry
var transformed = geometry.Transform(
Matrix3x2.CreateRotation((float)Math.PI / 4, new Vector2(50, 50)));
// Compute bounds
var bounds = geometry.ComputeBounds();
// Compute area
var area = geometry.ComputeArea();
// Hit testing
bool containsPoint = geometry.FillContainsPoint(new Vector2(50, 50));
bool strokeContains = geometry.StrokeContainsPoint(new Vector2(0, 50), 5);
}
```
--------------------------------
### Configure CanvasAnimatedControl for Game Loop Animation
Source: https://context7.com/microsoft/win2d/llms.txt
Set up CanvasAnimatedControl in XAML to manage a game loop with Update and Draw events. Configure fixed timestep and resource creation.
```xml
```
--------------------------------
### Playback CanvasCommandList and Use as Effect Source
Source: https://context7.com/microsoft/win2d/llms.txt
Draw a CanvasCommandList to a CanvasDrawingSession and use it as the source for a visual effect like GaussianBlurEffect. Requires Win2D effects pipeline.
```csharp
void DrawCommandList(CanvasDrawingSession ds)
{
// Play back recorded commands
ds.DrawImage(commandList, 0, 0);
// Can be used as effect source
var blur = new GaussianBlurEffect
{
Source = commandList,
BlurAmount = 5
};
ds.DrawImage(blur, 300, 0);
}
```
--------------------------------
### Draw Basic Shapes and Apply Transformations with CanvasDrawingSession
Source: https://context7.com/microsoft/win2d/llms.txt
Utilize CanvasDrawingSession to render lines, rectangles, ellipses, and circles. Demonstrates clearing the canvas, applying transformations, and controlling blend modes.
```csharp
void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
var ds = args.DrawingSession;
// Clear the canvas
ds.Clear(Colors.Navy);
// Draw lines
ds.DrawLine(0, 0, 200, 200, Colors.White);
ds.DrawLine(new Vector2(0, 200), new Vector2(200, 0), Colors.Yellow, 3);
// Draw rectangles
ds.DrawRectangle(50, 50, 100, 80, Colors.Red);
ds.FillRectangle(new Rect(160, 50, 100, 80), Colors.Green);
// Draw rounded rectangles
ds.DrawRoundedRectangle(50, 150, 100, 80, 10, 10, Colors.Cyan, 2);
ds.FillRoundedRectangle(160, 150, 100, 80, 15, 15, Colors.Magenta);
// Draw ellipses and circles
ds.DrawEllipse(100, 300, 50, 30, Colors.Orange, 3);
ds.FillCircle(new Vector2(220, 300), 40, Colors.Purple);
// Apply transformations
var previousTransform = ds.Transform;
ds.Transform = Matrix3x2.CreateRotation((float)Math.PI / 4, new Vector2(400, 200));
ds.FillRectangle(350, 150, 100, 100, Colors.LimeGreen);
ds.Transform = previousTransform; // Reset to default
// Set blend mode
ds.Blend = CanvasBlend.Add;
ds.FillCircle(300, 300, 50, Color.FromArgb(128, 255, 0, 0));
ds.FillCircle(340, 300, 50, Color.FromArgb(128, 0, 255, 0));
ds.Blend = CanvasBlend.SourceOver; // Reset to default
// Antialiasing control
ds.Antialiasing = CanvasAntialiasing.Aliased;
ds.DrawLine(0, 400, 500, 400, Colors.White);
ds.Antialiasing = CanvasAntialiasing.Antialiased;
}
```
--------------------------------
### Create a Complex Star Path
Source: https://context7.com/microsoft/win2d/llms.txt
Builds a complex star shape using CanvasPathBuilder by adding lines sequentially. The path is then closed and converted into a CanvasGeometry.
```csharp
// Create complex paths with CanvasPathBuilder
CanvasGeometry CreateCustomPath(ICanvasResourceCreator creator)
{
var pathBuilder = new CanvasPathBuilder(creator);
// Star shape
pathBuilder.BeginFigure(100, 0);
pathBuilder.AddLine(130, 70);
pathBuilder.AddLine(200, 70);
pathBuilder.AddLine(145, 115);
pathBuilder.AddLine(165, 190);
pathBuilder.AddLine(100, 145);
pathBuilder.AddLine(35, 190);
pathBuilder.AddLine(55, 115);
pathBuilder.AddLine(0, 70);
pathBuilder.AddLine(70, 70);
pathBuilder.EndFigure(CanvasFigureLoop.Closed);
return CanvasGeometry.CreatePath(pathBuilder);
}
```
--------------------------------
### Efficient Sprite Rendering with CanvasSpriteBatch
Source: https://context7.com/microsoft/win2d/llms.txt
Optimizes drawing many sprites from the same source bitmap. Check for support and use CanvasSpriteSortMode for performance. Supports tinting, rotation, origin, and scaling.
```csharp
CanvasBitmap spriteSheet;
void DrawSprites(CanvasDrawingSession ds)
{
// Check if sprite batch is supported
if (!CanvasSpriteBatch.IsSupported(ds.Device))
return;
// Create sprite batch with sorting for better performance
using (var spriteBatch = ds.CreateSpriteBatch(CanvasSpriteSortMode.Bitmap))
{
// Draw many sprites efficiently
for (int i = 0; i < 1000; i++)
{
float x = (i % 50) * 20;
float y = (i / 50) * 20;
// Source rectangle from sprite sheet (32x32 sprites)
var sourceRect = new Rect((i % 4) * 32, 0, 32, 32);
// Draw sprite with position, source rect, tint, rotation, origin, scale
spriteBatch.Draw(
spriteSheet,
new Vector2(x, y),
sourceRect,
Colors.White,
0, // Rotation
new Vector2(16, 16), // Origin
new Vector2(1, 1), // Scale
CanvasSpriteFlip.None
);
}
}
}
// Particle system using sprite batch
class Particle
{
public Vector2 Position;
public Vector2 Velocity;
public float Rotation;
public float Scale;
public Color Tint;
public float Life;
}
void DrawParticles(CanvasDrawingSession ds, List particles,
CanvasBitmap particleTexture)
{
using (var batch = ds.CreateSpriteBatch())
{
foreach (var p in particles)
{
var tint = Color.FromArgb(
(byte)(p.Tint.A * p.Life),
p.Tint.R, p.Tint.G, p.Tint.B);
batch.Draw(
particleTexture,
p.Position,
particleTexture.Bounds,
tint,
p.Rotation,
new Vector2(particleTexture.Size.Width / 2,
particleTexture.Size.Height / 2),
new Vector2(p.Scale, p.Scale),
CanvasSpriteFlip.None
);
}
}
}
```
--------------------------------
### Draw and Fill Primitive Geometries
Source: https://context7.com/microsoft/win2d/llms.txt
Creates and draws various primitive geometric shapes like rectangles, rounded rectangles, ellipses, and circles. Requires a CanvasDrawingSession and an ICanvasResourceCreator.
```csharp
using Microsoft.Graphics.Canvas.Geometry;
void DrawGeometry(CanvasDrawingSession ds, ICanvasResourceCreator creator)
{
// Create primitive geometries
var rectangle = CanvasGeometry.CreateRectangle(creator, 50, 50, 100, 80);
var roundedRect = CanvasGeometry.CreateRoundedRectangle(creator,
200, 50, 100, 80, 15, 15);
var ellipse = CanvasGeometry.CreateEllipse(creator, 400, 90, 60, 40);
var circle = CanvasGeometry.CreateCircle(creator, 550, 90, 50);
// Draw and fill geometries
ds.DrawGeometry(rectangle, Colors.Red, 2);
ds.FillGeometry(roundedRect, Colors.Blue);
ds.DrawGeometry(ellipse, Colors.Green, 3);
ds.FillGeometry(circle, Colors.Purple);
// Create polygon
Vector2[] points = {
new Vector2(100, 200),
new Vector2(150, 300),
new Vector2(50, 300)
};
var triangle = CanvasGeometry.CreatePolygon(creator, points);
ds.FillGeometry(triangle, Colors.Orange);
}
```
--------------------------------
### Generate Procedural Checkerboard Texture
Source: https://context7.com/microsoft/win2d/llms.txt
Create a procedural texture, such as a checkerboard, by drawing onto a CanvasRenderTarget. This method is suitable for generating dynamic or repeating patterns.
```csharp
// Generate procedural texture
CanvasRenderTarget CreateCheckerboardTexture(ICanvasResourceCreator creator,
int size, int tileSize)
{
var texture = new CanvasRenderTarget(creator, size, size, 96);
using (var ds = texture.CreateDrawingSession())
{
ds.Clear(Colors.White);
for (int y = 0; y < size; y += tileSize)
{
for (int x = 0; x < size; x += tileSize)
{
if ((x / tileSize + y / tileSize) % 2 == 0)
{
ds.FillRectangle(x, y, tileSize, tileSize, Colors.Gray);
}
}
}
}
return texture;
}
```
--------------------------------
### Create CanvasRenderTarget with Specific Size
Source: https://context7.com/microsoft/win2d/llms.txt
Instantiate a CanvasRenderTarget with a specified width and height. This is useful for creating bitmaps for offscreen drawing.
```csharp
CanvasRenderTarget renderTarget;
void CreateRenderTarget(CanvasControl sender)
{
// Create render target with specific size
renderTarget = new CanvasRenderTarget(sender, 400, 300);
// Or with specific DPI and format
renderTarget = new CanvasRenderTarget(sender.Device, 400, 300, 96,
DirectXPixelFormat.B8G8R8A8UIntNormalized,
CanvasAlphaMode.Premultiplied);
}
```
--------------------------------
### Composite Multiple Images in Win2D
Source: https://context7.com/microsoft/win2d/llms.txt
Combines two images using the CompositeEffect with the 'SourceOver' mode. This is useful for layering images, such as placing a foreground image on top of a background.
```csharp
// Composite multiple images
CompositeEffect CreateComposite(CanvasBitmap background, CanvasBitmap foreground)
{
return new CompositeEffect
{
Sources = { background, foreground },
Mode = CanvasComposite.SourceOver
};
}
```
--------------------------------
### Create Sepia Tone Effect using ColorMatrixEffect
Source: https://context7.com/microsoft/win2d/llms.txt
Applies a sepia tone to an image using the ColorMatrixEffect. This effect allows for advanced color manipulation by defining a custom color transformation matrix.
```csharp
// Color matrix effect for advanced color manipulation
ColorMatrixEffect CreateSepiaEffect(ICanvasImage source)
{
return new ColorMatrixEffect
{
Source = source,
ColorMatrix = new Matrix5x4
{
M11 = 0.393f, M12 = 0.349f, M13 = 0.272f, M14 = 0,
M21 = 0.769f, M22 = 0.686f, M23 = 0.534f, M24 = 0,
M31 = 0.189f, M32 = 0.168f, M33 = 0.131f, M34 = 0,
M41 = 0, M42 = 0, M43 = 0, M44 = 1,
M51 = 0, M52 = 0, M53 = 0, M54 = 0
}
};
}
```
--------------------------------
### Win2D Event Handlers for Drawing
Source: https://context7.com/microsoft/win2d/llms.txt
Implement event handlers for CanvasControl to load resources asynchronously and perform drawing operations. Ensure proper cleanup by removing the control from the visual tree when the page is unloaded.
```csharp
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.UI;
using Microsoft.Graphics.Canvas.UI.Xaml;
using Windows.UI;
public sealed partial class MainPage : Page
{
CanvasBitmap backgroundImage;
public MainPage()
{
this.InitializeComponent();
}
void Canvas_CreateResources(CanvasControl sender, CanvasCreateResourcesEventArgs args)
{
// Track async resource loading
args.TrackAsyncAction(LoadResourcesAsync(sender).AsAsyncAction());
}
async Task LoadResourcesAsync(CanvasControl sender)
{
// Load bitmap from app package
backgroundImage = await CanvasBitmap.LoadAsync(sender, "Assets/background.png");
}
void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
var ds = args.DrawingSession;
// Draw loaded image
if (backgroundImage != null)
ds.DrawImage(backgroundImage, 0, 0);
// Draw shapes
ds.DrawEllipse(150, 100, 80, 40, Colors.Black, 3);
ds.FillRectangle(50, 50, 100, 60, Colors.Blue);
// Draw text
ds.DrawText("Hello Win2D!", 100, 150, Colors.White);
}
void Page_Unloaded(object sender, RoutedEventArgs e)
{
// Required cleanup to avoid memory leaks
canvasControl.RemoveFromVisualTree();
canvasControl = null;
}
```
--------------------------------
### Draw Image Effects on Canvas
Source: https://context7.com/microsoft/win2d/llms.txt
Renders the output of created image effects onto the drawing session. Effects can be drawn as full images or to specific rectangles on the canvas.
```csharp
// Draw effects
void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
var ds = args.DrawingSession;
// Draw effect output like any image
ds.DrawImage(blurEffect, 0, 0);
ds.DrawImage(saturationEffect, 300, 0);
// Effects can be drawn to specific rectangles
ds.DrawImage(transformEffect, new Rect(0, 300, 200, 200));
}
```
--------------------------------
### Draw Cached CanvasRenderTarget Multiple Times
Source: https://context7.com/microsoft/win2d/llms.txt
Efficiently draw a pre-rendered CanvasRenderTarget onto the screen multiple times using DrawImage. This leverages the offscreen bitmap for performance.
```csharp
void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
var ds = args.DrawingSession;
// Draw the cached render target multiple times efficiently
ds.DrawImage(renderTarget, 0, 0);
ds.DrawImage(renderTarget, 420, 0);
ds.DrawImage(renderTarget, 0, 320);
ds.DrawImage(renderTarget, 420, 320);
}
```
--------------------------------
### C# Win2D Draw Event Handler
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/README.md
Implement this C# method to handle the Draw event for a CanvasControl. It demonstrates drawing an ellipse and text using the CanvasDrawEventArgs.
```cs
void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3);
args.DrawingSession.DrawText("Hello, world!", 100, 100, Colors.Yellow);
}
```
--------------------------------
### Draw Complex Content to CanvasRenderTarget
Source: https://context7.com/microsoft/win2d/llms.txt
Obtain a drawing session from a CanvasRenderTarget to draw complex graphics offscreen. Ensure the drawing session is disposed to finalize the drawing.
```csharp
void DrawToRenderTarget()
{
// Create a drawing session for the render target
using (var ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.Transparent);
// Draw complex content once
for (int i = 0; i < 100; i++)
{
float x = i * 4;
ds.DrawLine(x, 0, x, 300, Colors.Blue, 1);
}
ds.FillCircle(200, 150, 100, Colors.Red);
ds.DrawText("Cached Content", 100, 140, Colors.White);
}
// Drawing session must be closed before using render target
}
```
--------------------------------
### Blend Two Images in Win2D
Source: https://context7.com/microsoft/win2d/llms.txt
Blends two images using the BlendEffect with the 'Multiply' mode. This effect is suitable for combining images where the resulting color is a product of the input colors.
```csharp
// Blend two images
BlendEffect CreateBlend(ICanvasImage background, ICanvasImage foreground)
{
return new BlendEffect
{
Background = background,
Foreground = foreground,
Mode = BlendEffectMode.Multiply
};
}
```
--------------------------------
### C++/WinRT Win2D Draw Event Handler
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/README.md
This C++/WinRT method implements the Draw event for a CanvasControl. It shows how to draw an ellipse and text using the CanvasDrawEventArgs with WinRT syntax.
```cpp
void MainPage::CanvasControl_Draw(CanvasControl const& sender, CanvasDrawEventArgs const& args)
{
args.DrawingSession().DrawEllipse(155, 115, 80, 30, Colors::Black(), 3);
args.DrawingSession().DrawText(L"Hello, world!", 100, 100, Colors::Yellow());
}
```
--------------------------------
### C++/CX Win2D Draw Event Handler
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/README.md
This C++/CX method handles the Draw event for a CanvasControl, similar to the C# version. It draws an ellipse and text using the CanvasDrawEventArgs.
```cpp
void MainPage::CanvasControl_Draw(CanvasControl^ sender, CanvasDrawEventArgs^ args)
{
args->DrawingSession->DrawEllipse(155, 115, 80, 30, Colors::Black, 3);
args->DrawingSession->DrawText("Hello, world!", 100, 100, Colors::Yellow);
}
```
--------------------------------
### VB.NET Win2D Draw Event Handler
Source: https://github.com/microsoft/win2d/blob/winappsdk/main/README.md
This VB.NET method handles the Draw event for a CanvasControl. It demonstrates drawing an ellipse and text using the CanvasDrawEventArgs.
```vb
Sub canvasControl_Draw(sender As CanvasControl, args As CanvasDrawEventArgs)
args.DrawingSession.DrawEllipse(155, 115, 80, 30, Colors.Black, 3)
args.DrawingSession.DrawText("Hello, world!", 100, 100, Colors.Yellow)
End Sub
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.