【问题标题】:Convert Xamarin.Forms measure units to pixels将 Xamarin.Forms 度量单位转换为像素
【发布时间】:2020-08-27 08:44:28
【问题描述】:

如何将view.WidthRequest 值转换为平台像素?我正在寻找像Device.ConvertToPixels(10) 这样的方法。

我想将它用于 SkiaSharp 绘图。例如,我想在(xamarin.forms 单位)中绘制笔画 = 10 的圆圈,该圆圈将在绘制时转换为像素。

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    将 MainDisplayInfo.Dencity 乘以 (xamarin.forms 单位) 即可得到像素。

    我做了一个方法。

        double XamDIUConvertToPixels(double XamDIU)
        {
            var desplayinfo = DeviceDisplay.MainDisplayInfo;
            var pixcels = desplayinfo.Density * XamDIU;
            return pixcels;
        }
    

    DeviceDisplay 必须在 UI 线程上完成,否则 iOS 会抛出异常。

    阅读: https://docs.microsoft.com/en-us/xamarin/essentials/device-display?tabs=ios#platform-differences

    【讨论】:

      【解决方案2】:

      你也可以在顶部画一个比例,然后使用你喜欢的任何单位。

      例如,在 2x 显示器上,您可以执行 canvas.Scale(2) 然后像 1x 一样绘制。

      在 Xamarin.Forms 绘制事件的情况下,事件 args 包含您需要的所有信息:

      canvas.Scale(e.Info.Width / view.Width);
      

      另外,你可以看看这篇博文,我展示了一些东西:https://dotnetdevaddict.co.za/2020/01/12/who-cares-about-the-view-anyway/

      【讨论】:

        【解决方案3】:

        你可以试试下面的代码:

        在安卓中:

        var dp = 100;
                int pixel = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, dp, this.Resources.DisplayMetrics);
        

        在 Xamarin.Forms 中,尝试使用依赖服务。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction

        【讨论】:

        • iOS 怎么样?
        • 对于ios,无需转换。你得到的值的格式是像素。
        猜你喜欢
        • 1970-01-01
        • 2011-03-28
        • 2010-10-01
        • 1970-01-01
        • 2020-05-07
        • 2013-04-09
        • 1970-01-01
        • 2012-03-11
        • 2011-10-24
        相关资源
        最近更新 更多