微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

确保 SkiaSharp 字体和 Xamarin Forms 默认字体匹配

如何解决确保 SkiaSharp 字体和 Xamarin Forms 默认字体匹配

我在 Xamarin Forms 中使用 SkiaSharp。我的目标是确保 Xamarin 控件中显示的字体,例如一个标签,匹配 SkiaSharp 绘图中使用的字体。

此外,我想使用认字体,以便应用在其各自的平台上看起来正确并符合用户偏好。

在我的简单应用程序中,我有一些 Xamarin 标签一个由 SkiaSharp 绘制的自定义控件。尽管它们非常接近,但两者具有不同的字体。 SkiaSharp 具有相同的外观,但体积要小 10%。而且 Xamarin 具有更广泛的抗锯齿功能

查看截图片段(上:SkiaSharp,下:Xamarin):

top:SkiaSharp,bottom:Xamarin

我不知道如何解决这个问题。至少有几种方法

  1. 如何确定 Xamarin 标签使用的字体?如果我能确定这一点,我应该可以为 SkiaSharp 绘图设置它。
  2. 或者,如何将 Xamarin 字体设置为 SkiaSharp 使用的字体。我可以在运行时从 SkiaSharp 获取字体系列,但我不知道如何在运行时在 Xamarin 中设置它。

我想第三种选择是通过 SkiaSharp 处理所有字体。但是,我将无法使用任何显示文本的 Xamarin 控件。

解决方法

通常,SkiaSharp 使用默认的系统文本字体来绘制文本。

如果您可以将 TextSize 设置为适合默认的 FontSize,您将看到它们将显示相同的内容。

看看这个截图:

enter image description here

Xaml 中,上面的一个是 Label,下面的一个是 SKCanvasView

<Label Text="Hello SkiaSharp!" x:Name="mylabel" VerticalOptions="Start" FontSize="Large" HorizontalOptions="CenterAndExpand" />
<forms:SKCanvasView PaintSurface="OnCanvasViewPaintSurface" />

OnCanvasViewPaintSurface 方法是:

void OnCanvasViewPaintSurface(object sender,SKPaintSurfaceEventArgs args)
{
    SKImageInfo info = args.Info;
    SKSurface surface = args.Surface;
    SKCanvas canvas = surface.Canvas;

    canvas.Clear();

    string str = "Hello SkiaSharp!";

    // Create an SKPaint object to display the text
    SKPaint textPaint = new SKPaint
    {
        Color = SKColors.Chocolate
    };

    // Adjust TextSize property so text is 90% of screen width
    float textWidth = textPaint.MeasureText(str);
    //textPaint.TextSize = 0.9f * info.Width * textPaint.TextSize / textWidth;
    textPaint.TextSize = (float)((float)mylabel.FontSize*(2.6));

    //textPaint.Typeface = SKTypeface.FromFamilyName("monospace");

    // Find the text bounds
    SKRect textBounds = new SKRect();
    textPaint.MeasureText(str,ref textBounds);

    // Calculate offsets to center the text on the screen
    float xText = info.Width / 2 - textBounds.MidX;
    float yText = info.Height / 2 - textBounds.MidY;

    // And draw the text
    canvas.DrawText(str,xText,yText,textPaint);

    // Create a new SKRect object for the frame around the text
    SKRect frameRect = textBounds;
    frameRect.Offset(xText,yText);
    frameRect.Inflate(10,10);

    // Create an SKPaint object to display the frame
    SKPaint framePaint = new SKPaint
    {
        Style = SKPaintStyle.Stroke,StrokeWidth = 5,Color = SKColors.Blue
    };

    // Draw one frame
    canvas.DrawRoundRect(frameRect,20,framePaint);

    // Inflate the frameRect and draw another
    frameRect.Inflate(10,10);
    framePaint.Color = SKColors.DarkBlue;
    canvas.DrawRoundRect(frameRect,30,framePaint);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。