2017-06-23 35 views
0

我正嘗試在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

回答

0

我有一個適用於我的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; 
}