Rotate Image in Win2D

Md. Zakir Hossain 21 Reputation points
2020-06-16T08:16:47.99+00:00

I'm trying to rotate image but couldn't get expected result. I've tried with WIn2D but couldn't make image as expected.

public async void Rotate(string originalImagepath, Rect originalImageRect, float degrees)
    {
        int height = (int)Math.Sqrt(originalImageRect.Width * originalImageRect.Width + originalImageRect.Height * originalImageRect.Height);

        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasRenderTarget webCardImage = null;
        CanvasBitmap bitmap = null;
        var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
        Vector2 endpoint = new Vector2((float)originalImageRect.Width / 2, (float)originalImageRect.Height / 2);

        try
        {
            webCardImage = new CanvasRenderTarget(device, height, height, logicalDpi);
            using (var ds = webCardImage.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);

                using (FileStream imageStream = new FileStream(originalImagepath, FileMode.Open))
                {
                    IRandomAccessStream fileStream = imageStream.AsRandomAccessStream();
                    bitmap = await CanvasBitmap.LoadAsync(device, fileStream);
                }

                ICanvasImage image = new Transform2DEffect
                {
                    Source = bitmap,
                    TransformMatrix = Matrix3x2.CreateRotation(degrees, endpoint),
                };
                var sourceRect = image.GetBounds(ds);
                ds.DrawImage(image, new Rect(originalImageRect.X, originalImageRect.Y, originalImageRect.Width, originalImageRect.Height), sourceRect, 1, CanvasImageInterpolation.HighQualityCubic);

            }
        }
        catch (Exception ex)
        {

        }
        //Save Image Code here
    }

I want rotate image as 30 degree. After executing my code i got unexpected result.

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. John Torjo 861 Reputation points
    2020-06-16T08:43:03.507+00:00

    I believe your code is correct. However, you need to convert your degrees to radian degrees:

    private static double radian(double degrees) {
        return degrees * Math.PI / 180d;
    }
    

    This should fix it.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.