简体   繁体   English

iOS使图像适合屏幕

[英]iOS Fit Image to Screen

I have an image that is 646x289 that I am trying to fit in the screen with respect to its aspect ratio. 我有一个646x289的图像,该图像要根据屏幕的长宽比进行调整。

Here is my current approach: 这是我目前的方法:

Controller: 控制器:

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

When this loads, the image is way too large and doesn't fit in the screen. 加载时,图像太大,不适合屏幕。

I am constructing all of my interfaces in C# (using Xamarin) as well so I need to be able to do this using frames and bounds. 我也正在C#中构造所有接口(使用Xamarin),因此我需要能够使用框架和界限做到这一点。

Use the ContentMode of the UIImageView to control how the image is scaled and you can skip the manual resizing: 使用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...
}

Ref: https://developer.apple.com/reference/uikit/uiviewcontentmode 参考: https : //developer.apple.com/reference/uikit/uiviewcontentmode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM