问题描述
我正在使用Xamarin表单,并且我有一个项目要求字体大小为32像素。我一直在Google上搜索,但是找不到如何在Xamarin设备无关的单位中转换此像素的答案。我将不胜感激。
谢谢。
解决方法
您可以使用 custom renderer 调用本机方法来设置32个像素。基于 Button 控件,您可以在Xamaarin的形式如下:
Button
然后,Andoird解决方案如下创建自定义rendere类:
public class MyButton : Button
{
}
关于其他控件,还可以创建自己的自定义渲染器。
================================更新============= ==================
可以将[assembly: ExportRenderer(typeof(Xamarin.Forms.MyButton),typeof(CustomButtonRenderer))]
namespace AppShellTest.Droid
{
[Obsolete]
public class CustomButtonRenderer: ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
// do whatever you want to the UITextField here!
Control.SetTextSize(Android.Util.ComplexUnitType.Px,32);
}
}
}
}
转换为dp
或将px
转换为px
的方法,您可以检查其是否适合您。
dp
然后渲染器代码将是:
public int dip2px(Context context,float dpValue)
{
float scale = context.Resources.DisplayMetrics.Density;
return (int)(dpValue * scale + 0.5f);
}
public int px2dip(Context context,float pxValue)
{
float scale = context.Resources.DisplayMetrics.Density;
return (int)(pxValue / scale + 0.5f);
}
在 MainActivity 中声明的 MainActivity.instance 表示MainActivity的实例。
public class CustomButtonRenderer: ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
// do whatever you want to the UITextField here!
Control.SetTextSize(Android.Util.ComplexUnitType.Px,dip2px(32));
}
}
public int dip2px(float dpValue)
{
float scale = MainActivity.instance.Resources.DisplayMetrics.Density;
return (int)(dpValue * scale + 0.5f);
}
}
,
Xamarin到处都使用DIU(与设备无关的单元)。 看看https://docs.microsoft.com/en-us/xamarin/xamarin-forms/creating-mobile-apps-xamarin-forms/summaries/chapter05
我遇到一个类似的问题,并通过反复试验发现, Xamarin.Essentials.DeviceDisplay.MainDisplayInfo.Density 返回设备上每个DIU的像素数量(在iPod Touch,诺基亚8上进行了测试和Firetablet)。
所以这应该是正确的:
myLabel.FontSize = 32 / Xamarin.Essentials.DeviceDisplay.MainDisplayInfo.Density;
但是正如Jason所说,您可能要检查您的要求,因为设备上的像素越多,字体越小。这就是为什么人们首先使用DIU的原因:-) 最好查看客户主页上的字体大小。也许以英寸,厘米或适合您的尺寸在那里进行测量,然后进行数学运算以将其转换为DIU(请参见上面的链接,64 DIU = 1厘米)。