Search code examples
c#wpf

What is the problem with zooming the window causing the rectangle to disappear?


When scaling the window with wpf, Part of the rectangle has disappeared

image.gif

How should I make the window display rectangles properly when zooming?

<Grid Background="Azure">
    <Grid x:Name="Grid01" HorizontalAlignment="Left"  Background="AliceBlue">
        <Image x:Name="ShowImage"  HorizontalAlignment="Left"/>
        <Rectangle x:Name="myRectangle"/>
    </Grid>
</Grid>

My backend code

myRectangle.Fill = null;
myRectangle.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red);
myRectangle.StrokeThickness = 3;
myRectangle.Width = nowWidth;
myRectangle.Height = nowHeight;
myRectangle.Margin = new Thickness(nowX, nowY - nowWidth / 2, 0, 0);
System.Windows.Media.RotateTransform rotateTransform = new(angle);
myRectangle.RenderTransform = rotateTransform;
myRectangle.RenderTransformOrigin = new System.Windows.Point(0, 0);//渲染动画的起点-取值范围0-1

Solution

  • if you wrap it all in a viewbox you the two controls wil scale with each other:

                    <Grid Background="Azure">
                        <Viewbox>                            
                            <Grid x:Name="Grid01" HorizontalAlignment="Left"  Width="1920" Height="1080" Background="HotPink">
                                <Image x:Name="ShowImage"/>
                                <Rectangle x:Name="myRectangle" Height="100" Width="100" Stroke="Red" StrokeThickness="5" Margin="10,10,0,0"/>
                            </Grid>
                        </Viewbox>
                    </Grid>