Search code examples
c#wpfscaletransform

ScaleTransform in WPF is rendering the wrong size


I am trying to understand why a ScaleTransform (testing under Windows Phone 8.0) is rendering using the control's parent dimensions, instead of the control itself. I have set up a demo app that shows this behaviour, as shown below.

The dimensions and hierarchy has a reason to be, that's why I manually set the Width and Height, as it's very close to the real app.

What I'd expect is that child1 (the yellow one), which is 768x1228 and has a scale of 0.625, would render itself as if it was 480x768, but what happens is that it renders like it was 300x480 (e.g., it is rendered at 0.625% of 480, instead of 768).

Any clues?

public partial class MainPage : PhoneApplicationPage
{
    private Grid root;

    public MainPage()
    {
        InitializeComponent();
        root = new Grid() {
            Width = 480,
            Height = 768,
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Top,
            Background = new SolidColorBrush(Colors.Blue)
        };
        Content = root;
        Loaded += MainPage_Loaded;
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        var parent1 = new Grid {
            Background = new SolidColorBrush(Colors.Red),
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Top,
            Width = 480,
            Height = 768
        };

        root.Children.Add(parent1);

        var child1 = new Grid {
            Background = new SolidColorBrush(Colors.Yellow),
            Width = 768,
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Top,
            Height = 1228,
            RenderTransform = new ScaleTransform() {
                CenterX = 0,
                CenterY = 0,
                ScaleX = 0.625,
                ScaleY = 0.625
            }
        };

        parent1.Children.Add(child1);
    }
}    

Solution

  • Well, looks like it's all due to the fact that the Grid component clip its child elements, as mentioned at http://wpf.2000things.com/tag/clipping. After I changed the code to have a Canvas aground my Grid, the app worked as expected.

    I still find this "solution" strange, though.