iOS适合图像到屏幕

时间:2016-11-08 14:47:48

标签: c# ios image user-interface xamarin

我有一个646x289的图像,我试图在屏幕上调整其宽高比。

这是我目前的做法:

控制器:

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 个答案:

答案 0 :(得分:2)

使用ContentMode的{​​{1}}来控制图像的缩放方式,您可以跳过手动调整大小:

UIImageView

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