- 1 year ago
UWP Canvas Pixel Manipulation
In UWP (Universal Windows Platform), you can perform pixel manipulation on a Canvas
by using the WriteableBitmap
class. Here's an example of how you can manipulate pixels on a Canvas
:
- Add a
Canvas
element to your XAML file:
xml<Canvas x:Name="myCanvas" Width="400" Height="300" />
- In your code-behind file (C#), manipulate the pixels of the
Canvas
using aWriteableBitmap
:
csharpusing Windows.UI.Xaml.Media.Imaging;
using Windows.UI;
// Get a reference to the Canvas in your XAML
Canvas myCanvas = this.myCanvas;
// Create a WriteableBitmap with the same dimensions as the Canvas
WriteableBitmap bitmap = new WriteableBitmap((int)myCanvas.Width, (int)myCanvas.Height);
// Lock the bitmap to enable pixel manipulation
bitmap.Lock();
// Get the pixel buffer of the bitmap
byte[] pixelBuffer = bitmap.PixelBuffer.ToArray();
// Get the width and height of the bitmap
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
// Manipulate the pixels (e.g., invert colors)
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int index = (y * width + x) * 4; // Each pixel is represented by 4 bytes (RGBA)
byte r = pixelBuffer[index + 2];
byte g = pixelBuffer[index + 1];
byte b = pixelBuffer[index];
byte a = pixelBuffer[index + 3];
// Invert colors
pixelBuffer[index + 2] = (byte)(255 - r);
pixelBuffer[index + 1] = (byte)(255 - g);
pixelBuffer[index] = (byte)(255 - b);
}
}
// Update the pixel buffer of the bitmap
using (Stream stream = bitmap.PixelBuffer.AsStream())
{
stream.Write(pixelBuffer, 0, pixelBuffer.Length);
}
// Unlock the bitmap
bitmap.Unlock();
// Display the bitmap on the Canvas
Image image = new Image()
{
Source = bitmap
};
Canvas.SetLeft(image, 0);
Canvas.SetTop(image, 0);
myCanvas.Children.Add(image);
In this example, a WriteableBitmap
is created with the same dimensions as the Canvas
. The PixelBuffer
property is then accessed to retrieve the pixel buffer as an array of bytes. The bytes are manipulated to invert the colors (in this case). Finally, the modified pixel buffer is written back to the WriteableBitmap
, which is then displayed on the Canvas
.
Make sure to include the required using
statements at the top of your code-behind file to access the necessary classes and namespaces.
By using the WriteableBitmap
class and manipulating the pixel buffer, you can perform various pixel-level operations on a Canvas
in UWP.