Search code examples
iosxamarinxamarin.iosnsimagexamarin.mac

Xamarin Mac - Resize Image


I am trying to resize an image in my Mac-App as I did before in an iOS-App. The problem is that NSImage does not contain all methods UIImage do. Here is the code I used for iOS

public static UIImage MaxResizeImage(this UIImage sourceImage, float maxWidth, float maxHeight)
    {
        var sourceSize = sourceImage.Size;
        var maxResizeFactor = Math.Max(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
        if (maxResizeFactor > 1) return sourceImage;
        float width = (float)(maxResizeFactor * sourceSize.Width);
        float height = (float)(maxResizeFactor * sourceSize.Height);
        UIGraphics.BeginImageContext(new SizeF(width, height));
        sourceImage.Draw(new RectangleF(0, 0, width, height));
        var resultImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return resultImage;
    }

How can I rewrite it for a Mac-App? Thanks for your help


Solution

  • I have a working function for my Mac app, rewrote it to fit your function. Haven't tested this version but it should work.

    public static NSImage MaxResizeImage(this NSImage sourceImage, float maxWidth, float maxHeight)
    {
        var sourceSize = sourceImage.Size;
        var maxResizeFactor = Math.Max(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
        if (maxResizeFactor > 1) return sourceImage;
        float width = (float)(maxResizeFactor * sourceSize.Width);
        float height = (float)(maxResizeFactor * sourceSize.Height);
        var targetRect = new CoreGraphics.CGRect(0,0,width, height);
        var newImage = new NSImage (new CoreGraphics.CGSize (width, height));
        newImage.LockFocus ();
        sourceImage.DrawInRect(targetRect, CoreGraphics.CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
        newImage.UnlockFocus ();
    
        return newImage;
    }