【问题标题】:iOS Fit Image to ScreeniOS 使图像适合屏幕
【发布时间】:2017-03-22 06:05:14
【问题描述】:

我有一张 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)构建我的所有接口,所以我需要能够使用框架和边界来做到这一点。

【问题讨论】:

    标签: c# ios image user-interface 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

    【讨论】:

    • 这就是我要找的答案,非常感谢先生!
    • @kformeck np,很高兴它有帮助......然后自己调整大小很容易,它被 iOS 加速和缓存......
    猜你喜欢
    • 2016-08-09
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2014-11-04
    相关资源
    最近更新 更多