// First, test this in YourApp.Android project's MainActivity.cs.
// Returns "1" at default scale. Larger value when font should be larger.
public float CurrentFontScale()
{
Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics();
// Deprecated. But if it compiles, it works.
WindowManager.DefaultDisplay.GetMetrics(metrics);
float scaledDensity = metrics.ScaledDensity;
return scaledDensity;
}
// Call it from here:
protected override void OnCreate(Bundle bundle){
{
...
base.OnCreate(bundle);
float fontScale = CurrentFontScale();
...
}
// --- Auto-fit Skia text. ---
// These are typically parameters.
string somestring = "Hello, World";
float MaxAllowedWidth = 100; // Pixels.
float fontSize = 20 * fontScale;
SKFont font = new SKFont(typeface, fontSize);
SKPaint textPaint = new SKPaint(font);
float textWidth = textPaint.MeasureText(somestring);
if (textWidth > MaxAllowedWidth)
{
// --- Shrink as needed. ---
// "Floor" to avoid being slightly too wide sometimes.
fontSize = Math.Floor(fontSize * MaxAllowedWidth / textWidth);
font = new SKFont(typeface, fontSize);
textPaint = new SKPaint(font);
// OPTIONAL VERIFY: This should now be less than MaxAllowedWidth.
textWidth = textPaint.MeasureText(somestring);
}
... paint the text ...
1条答案
按热度按时间vxqlmq5t1#
我所知道的找到缩放的唯一方法是通过已弃用的Android API:
将所有Skia字体大小乘以此值。
确认代码在
MainActivity.cs
中工作后,要在跨平台Xamarin项目中使用它,请创建一个Xamarin.Forms DependencyService,如何做超出了本答案的范围。作为一个实际问题,考虑“限制”给定字体大小的增长。否则,布局会变得困难。例如,
myFontSize = Math.Min(20 * fontScale, 48);
用于文本字符串,如果字体大小大于48,则会太大。另一种方法是使用
SKPaint.MeasureText(somestring)
,在创建了一个具有所需字体大小的skpaint之后,如果文本太长,则限制fontSize: