1

I'm working on an image viewer in C# WPF that can zoom and crop images. I'd like to be able to make the two work together, but I don't know how to calculate that.

To zoom an image, it is done by modifying TranslateTransform and ScaleTransform X & Y values. Inspired by this answer https://stackoverflow.com/a/6782715/2923736

The crop function is done by calculating TopLeftX, TopRightY, BottomRightX, BottomLeftY that has been drawn on screen.

The size and aspect ratio calculation is done like so:

maxWidth = Math.Min(ScreenWidth, imageWidth);
maxHeight = Math.Min(ScreenHeight, imageHeight);

AspectRatio = Math.Min(maxWidth / imageWidth, maxHeight / imageHeight);
ImageWidth = imageWidth * AspectRatio;
ImageHeight = imageHeight * AspectRatio;

I use this code to calculate the cropped area, but don't know how to put TranslateTransform and ScaleTransform X & Y values into the formula.

internal static Int32Rect? GetCrop()
{
    // Contains the dimensions and coordinates of cropped area
    var cropArea = CropService.GetCroppedArea(); 

    if (cropArea == null) { return null; }

    int x, y, width, height;

    x = Convert.ToInt32(cropArea.CroppedRectAbsolute.X / AspectRatio);
    y = Convert.ToInt32(cropArea.CroppedRectAbsolute.Y / AspectRatio);

    switch (Rotateint) // Degress the image has been rotated by
    {
        case 0:
        case 180:
            width = Convert.ToInt32(cropArea.CroppedRectAbsolute.Width / AspectRatio);
            height = Convert.ToInt32(cropArea.CroppedRectAbsolute.Height / AspectRatio);
            break;
        default:
            width = Convert.ToInt32(cropArea.CroppedRectAbsolute.Height / AspectRatio);
            height = Convert.ToInt32(cropArea.CroppedRectAbsolute.Width / AspectRatio);
            break;
    }

    return new Int32Rect(x, y, width, height);
}

Example of image being cropped, PicView

Example of image being cropped, where it has been resized to fit the window and zoomed in by 20%. I need to calculate that, so it can be saved on the user's hard disk.

Ruben
  • 55
  • 8

0 Answers0