xamarin Skia Sharp DrawText不考虑Android辅助功能设置(字体大小)

xe55xuns  于 2022-12-16  发布在  Android
关注(0)|答案(1)|浏览(130)

如果用户在android辅助功能设置中将字体大小从默认值更改为大或最大,则所有标签都将按比例放大。但使用DrawText方法在画布上绘制文本无效。
这是预期的行为吗?我以为用skia sharp绘制的文本也会按比例放大。
在skia sharp中处理android无障碍功能变化的正确方法是什么?
谢谢

vxqlmq5t

vxqlmq5t1#

我所知道的找到缩放的唯一方法是通过已弃用的Android API:

// 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();

    ...
}

将所有Skia字体大小乘以此值。
确认代码在MainActivity.cs中工作后,要在跨平台Xamarin项目中使用它,请创建一个Xamarin.Forms DependencyService,如何做超出了本答案的范围。
作为一个实际问题,考虑“限制”给定字体大小的增长。否则,布局会变得困难。例如,myFontSize = Math.Min(20 * fontScale, 48);用于文本字符串,如果字体大小大于48,则会太大。
另一种方法是使用SKPaint.MeasureText(somestring),在创建了一个具有所需字体大小的skpaint之后,如果文本太长,则限制fontSize:

// --- 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 ...

相关问题