#1,062 – Scaling a Canvas Using a ViewBox
April 30, 2014 3 Comments
A ViewBox is typically used to scale a panel containing other elements. One common use of a ViewBox is to scale the contents of a Canvas panel.
We might include several elements within a Canvas that has an explicit size.
If we re-size the window, however, the canvas stays the same size.
We could have had the Canvas stretch to fill the remaining area, but its elements would still be the same size.
We can get the elements within the Canvas to scale by wrapping the Canvas in a ViewBox.
<DockPanel> <Label DockPanel.Dock="Top" Background="LightGray" Content="Stuff at top of window here" VerticalAlignment="Top"/> <Label DockPanel.Dock="Bottom" Background="AliceBlue" Content="Bottom stuff down here" VerticalAlignment="Bottom"/> <Viewbox> <Canvas Background="Bisque" Width="200" Height="100"> <Line X1="5" Y1="5" X2="195" Y2="95" Stroke="Black"/> <Label Canvas.Left="80" Canvas.Top="5" Content="Howdy"/> <Ellipse Height="30" Width="50" Stroke="Blue" StrokeThickness="2" Canvas.Left="140" Canvas.Top="5"/> </Canvas> </Viewbox> </DockPanel>
Now when we resize the window, everything within the Canvas is scaled.
👋 Looking for a way to control the shape of the ViewBox. E.g. is it possible to have a circular one, such that any zoom-in and zoom-out image manipulation stays with the circular boundary?
To answer my own q: What I really wanted was to control the shape of a Canvas so I used the Clip property: ImageCanvas.Clip = new EllipseGeometry(new Point(200, 200), 200, 200);
I haven’t seen an example of this, but you might try posting the question on stack overflow.