2016-11-08 177 views
1

我有一張646x289的圖像,我試圖在屏幕寬高比方面適合它。iOS適合屏幕的圖像

這是我目前的做法:

控制器:

public override void ViewDidLayoutSubviews() 
{ 
    base.ViewDidLayoutSubviews(); 
    _imnLogo.ContentMode = UIViewContentMode.ScaleAspectFit; 
    _imnLogo.SizeToFit(); 
    _imnLogo.Frame = new CGRect(
     View.Bounds.Left + 2 * Globals.MarginGrid, 
     View.Bounds.Top + Globals.MarginGrid, 
     _scaledImage.Size.Width, _scaledImage.Size.Height); 
} 

public override void LoadView() 
{ 
    base.LoadView(); 
    _scaledImage = MaxResizeImage(
     UIImage.FromFile("imn_logo.png"), (float) View.Bounds.Width, (float) View.Bounds.Height); 

    _imnLogo = new UIImageView(_scaledImage); 
    View.AddSubview(_imnLogo); 
} 

public UIImage MaxResizeImage(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; 

    var width = maxResizeFactor * sourceSize.Width; 
    var height = maxResizeFactor * sourceSize.Height; 
    UIGraphics.BeginImageContext(new SizeF((float) width, (float) height)); 
    sourceImage.Draw(new RectangleF(0, 0, (float) width, (float) height)); 
    var resultImage = UIGraphics.GetImageFromCurrentImageContext(); 
    UIGraphics.EndImageContext(); 
    return resultImage; 
} 

當這種負載,形象的方式過大,不適合在屏幕上。我正在用C#構建我的所有接口(使用Xamarin),所以我需要能夠使用框架和邊界來實現這一點。

回答

1

使用UIImageViewContentMode來控制圖像如何縮放,您可以跳過手動調整大小:

public override void LoadView() 
{ 
    base.LoadView(); 
    _imnLogo = new UIImageView(UIImage.FromFile("imn_logo.png")); 
    _imnLogo.Frame = View.Frame; 
    _imnLogo.ContentMode = UIViewContentMode.ScaleAspectFill; 
    View.AddSubview(imageView); 
    View.SendSubviewToBack(imnLogo); // Do this if you want to place other `View`s on top of the logo... 
} 

編號:https://developer.apple.com/reference/uikit/uiviewcontentmode

+0

這是我一直在尋找的答案,非常感謝你很多先生! – kformeck

+0

@kformeck np,很高興它幫助...很容易,然後做一個調整自己,它是由iOS加速和緩存..... – SushiHangover