question

StefanoMora-9845 avatar image
0 Votes"
StefanoMora-9845 asked Paul-5034 edited

C# WPF - Rotate and fill a loaded bitmap

Hi everyone,
WPF project + C#.

In a StackPanel I have an Image that fills it.
At runtime I need to load a bitmap, rotate it and put in the Image control and fill it.
My code is:

                 BitmapImage bi = new BitmapImage(new Uri(modellino.image1, UriKind.RelativeOrAbsolute));
                 imgDescrizione.LayoutTransform = new RotateTransform(90);
                 imgDescrizione.Source = bi;

But in this way I'm able to rotate the image but its size is the one that fits not rotated the panel.

How can i solve it?

Thanks

dotnet-csharpdotnet-wpf-xaml
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Paul-5034 avatar image
0 Votes"
Paul-5034 answered Paul-5034 edited

You could use this method to get the new dimensions that imgDescrizione should have after the transform:

private static (int Width, int Height) GetRotatedDimensions(Image b, float angle) {
    var corners = new[] {
        new PointF(0, 0),
        new Point(b.Width, 0),
        new PointF(0, b.Height),
        new PointF(b.Width, b.Height)
    };

    var xc = corners.Select(p => Rotate(p, angle).X);
    var yc = corners.Select(p => Rotate(p, angle).Y);

    return (
        Width: (int)Math.Abs(xc.Max() - xc.Min()),
        Height: (int)Math.Abs(yc.Max() - yc.Min())
    );
}

/// <summary>
/// Rotates a point around the origin (0,0)
/// </summary>
private static PointF Rotate(PointF p, float angle) {
    // convert from angle to radians
    var theta = Math.PI * angle / 180;

    return new PointF(
        (float)(Math.Cos(theta) * (p.X) - Math.Sin(theta) * (p.Y)),
        (float)(Math.Sin(theta) * (p.X) + Math.Cos(theta) * (p.Y))
    );
}


Courtesy of SO: https://stackoverflow.com/questions/21066152/get-resulting-size-of-rotatetransform#answer-21070542

You'd just need to set the Width/Height of your imgDescrizione to match those returned by GetRotatedDimensions.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.