New to WinUI 3.0 -- I'm building a desktop app. The main window has a grid:
<Grid Name="mainGrid"
RowDefinitions="40,*"
ColumnDefinitions="100,*">
I use row 0 for a MenuBar and Column 0 for a vertical StackPanel containing buttons. The most important part of the grid is the cell at row 1 column 1. In that cell I need to show an image (from a file URI). I need the image to resize when the window is resized. My XAML for the image is:
<Image Name="myImage"
Source="C:\Users\leigh\OneDrive\Documents\Usa.jpg"
Stretch="Uniform"
Grid.Row="1"
Grid.Column="1">
</Image>
So far so good -- when I resize the window at run time, the image retains its original proportions as I resize the window. Now the hard part...
In code, I need to add various Shapes to the image in specific positions. For example, I need to add an Ellipse so that it appears, say, at 25% down from the top of the image and 65% to the right of the left side of the image. To imagine this, think of an image of a map of the United States. I want to place an ellipse right over Chicago. When the user resizes the window, the ellipse must still appear over Chicago -- but of course Chicago is now in a different absolute position on the computer screen due to the resizing.
Do I need to use a Canvas element to contain the Image element and then add my ellipse to the canvas at a specified position (I can recompute the Canvas-absolute coordinates in a SizeChanged event)? I have tried wrapping the Image element in a Canvas, but the Canvas does not resize when the window resizes. Does this mean I have to (1) get the absolute size of the image file, (2) figure out the "stretch math" to set the size of a canvas such that the image doesn't get distorted when I add it to the canvas, (3) figure out the new canvas-absolute position of the ellipse, etc. etc.
This all seems hopelessly complex. I just want to show a map of the U.S., draw an ellipse over Chicago at runtime, and keep the ellipse over Chicago as I resize the window (without distorting the shape of the U.S. of course).
Suggestions?
Basically you are on the right track. You don't need to have a canvas containing the image. You can put both the image and the canvas in the same grid "cell". Set the canvas's Horizontal and Vertical alignment to
Stretch. Then, you can hook to image's SizeChanged, and now you need to: