Xamarin 表单如何在屏幕上保留控件、图像和图标的间距和其他尺寸?

Xamarin forms how to retain spacing and other dimensions for controls, images and Icons across the screen?

iOS(4s 5s 及以上)是否需要针对不同屏幕尺寸使用不同的图像? 我们如何设置 images/Icons 的保留尺寸并在 iOS 中设置跨屏幕尺寸和分辨率的控件(使用 Xamarin 表单)。 请参考此以了解问题 Autolayout and proportional positioning

但我需要 xamarin 表单的解决方案。

我一直在使用不同的解决方案,例如:

命名规则

iphone 4 = "image.png"
iphone 5,6 (or retina) = "image@2x.png"
iphone 6+ = "image@3x.png"

使用依赖服务获取设备宽度和高度:

iOS

        public double Width
        {
            get
            {
                return UIScreen.MainScreen.Bounds.Width;
            }
        }

        public double Height
        {
            get
            {
                return UIScreen.MainScreen.Bounds.Height;
            }
        }

Android

  public double Width
    {
        get
        {
            var ctx = Forms.Context;
            var metrics = ctx.Resources.DisplayMetrics;
            return (ConvertPixelsToDp(metrics.WidthPixels));
        }
    }

    public double Height
    {
        get
        {
            var ctx = Forms.Context;
            var metrics = ctx.Resources.DisplayMetrics;

            return (ConvertPixelsToDp(metrics.HeightPixels));
        }
    }

然后我可以根据屏幕大小调整图像大小,例如 ScreenWidth/3。

对于 iOS 我使用 PaintCode。然后我在 Xamarin.Forms 中有一个名为:IconView 的视图和在 iOS 中使用 PaintCode 绘制图标(图像)的自定义渲染器。

当 Xamarin.Forms 调整 IconView 的大小时,自定义渲染器会重绘。 (您必须对 OnPropertyChanged 方法进行重绘:

// IconViewRenderer.cs
...
    protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged (sender, e);
        if (e.PropertyName == "Icon" || e.PropertyName == "X" || e.PropertyName == "Y" || e.PropertyName == "Width" || e.PropertyName == "Height")
            SetNeedsDisplay ();
    }

...
    public override void Draw (CoreGraphics.CGRect rect)
    {
        base.Draw (rect);

        var iconView = (IconView)Element;
        switch (iconView.Icon) {
        case IconView.IconKind.SomeIcon:
            PaintCode.DrawSomeIcon (rect);
        case IconView.IconKind.SomeOtherIcon:
            PaintCode.DrawSomeOtherIcon (rect);
        ....
        }
    }