Why squares inside canvas get distortion after page resize in uwp app

Gonzalez, Javier 40 Reputation points
2025-02-07T00:10:26.0366667+00:00

I made a UWP app and in its xaml file I wrote the following:

<Viewbox Height="60" Width="205" VerticalAlignment="Center" HorizontalAlignment="Center">

        <Canvas x:Name="Mycanvas" Height="60" Width="205" />

    </Viewbox>

The intention is to show in Mycanvas with a picture. The picture was created from a Writeablebitmap loaded in a canvas and then some polygons drawn.

When the app is running and I made a resize, the canvas remain in center but the polygons get moved. Is it supposed all remain inside the Viewbox and keep the ratio ?

Universal Windows Platform (UWP)
{count} votes

2 answers

Sort by: Most helpful
  1. Junjie Zhu - MSFT 20,441 Reputation points Microsoft Vendor
    2025-02-18T02:47:17.0733333+00:00

    Hello @Gonzalez, Javier ,

    To summarize the current problem. When the page is resized, the canvas remains centered but the polygon moves. This unexpected behavior can be avoided by drawing the polygon directly on the image streaming with WriteableBitmap.

    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);
    }
    
    

    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.


  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.