Hello @Gonzalez, Javier ,
Welcome to Microsoft Q&A!
Depending on your scenario, WriteableBitmap is more in line with your requirements. Here is a simple example.
private async void LoadImageAndDrawRectangle()
{
// Pick an image file
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
if (file == null) return;
// Load the image into a WriteableBitmap
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
var decoder = await BitmapDecoder.CreateAsync(stream);
var bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
await bitmap.SetSourceAsync(stream);
// Draw a rectangle on the image
//var rectangle = new Rectangle
//{
// Width = 100,
// Height = 100,
// Stroke = new SolidColorBrush(Windows.UI.Colors.Red),
// StrokeThickness = 5
//};
DrawRectangleOnBitmap(bitmap,100,200,50,80, Colors.Red);
Image ImageControl = new Image();
ImageControl.Source = bitmap;
Mycanvas.Children.Add(ImageControl);
//Mycanvas.Children.Add(rectangle);
//Canvas.SetLeft(rectangle, 50); // Set the position of the rectangle
//Canvas.SetTop(rectangle, 50);
}
}
public void DrawRectangleOnBitmap(WriteableBitmap bitmap, int x, int y, int width, int height, Color color)
{
using (var stream = bitmap.PixelBuffer.AsStream())
{
for (int i = 0; i < width; i++)
{
// Draw top and bottom sides
SetPixel(stream, bitmap.PixelWidth, x + i, y, color);
SetPixel(stream, bitmap.PixelWidth, x + i, y + height - 1, color);
}
for (int i = 0; i < height; i++)
{
// Draw left and right sides
SetPixel(stream, bitmap.PixelWidth, x, y + i, color);
SetPixel(stream, bitmap.PixelWidth, x + width - 1, y + i, color);
}
}
}
private void SetPixel(Stream stream, int width, int x, int y, Color color)
{
int index = (y * width + x) * 4;
stream.Seek(index, SeekOrigin.Begin);
stream.WriteByte(color.B);
stream.WriteByte(color.G);
stream.WriteByte(color.R);
stream.WriteByte(color.A);
}
In your latest question, I also tested using this code.
Thank you
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.