Xamarin Mac - 调整图像

问题描述:

我正尝试在iOS应用程序中调整我的Mac-App中的图像大小。问题是NSImage不包含UIImage所做的所有方法。这里是我用于iOS的代码Xamarin Mac - 调整图像

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; 
    } 

我该如何为Mac-App重写它?感谢您的帮助

+0

请接受anwser或添加评论,如果它不解决 – svn

我有一个适用于我的Mac应用程序的工作函数,将其重写为适合您的功能。没有测试过这个版本,但它应该可以工作。

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; 
}