How to draw rich text with Skia or SkiaSharp

2020-07-26 10:20发布

I want to draw rich text like iOS's Attributed Text or Xamarin.Forms's FormattedString with SkiaSharp, but I can't find how to.

I found the DrawText method, but it's for simple text rendering with one color and one font. No mixed colors and/or fonts and no styles like bold, italic, strike-through, or underline.

Do I have to do it with my own rich text rendering logic?

1条回答
放我归山
2楼-- · 2020-07-26 11:01

This is doable using the SKPaint type. Basically, as you draw, you set the properties on the paint:

var paint = new SKPaint();
paint.StrikeThruText = true;
paint.TextSize = 24;
paint.Color = SKColors.Yellow;
paint.UnderlineText = true;
paint.Typeface = SKTypeface.FromFamilyName(
    "Arial", 
    SKFontStyleWeight.Bold, 
    SKFontStyleWidth.Normal, 
    SKFontStyleSlant.Italic);

and then you can draw:

canvas.DrawText("Fancy Text", 30, 30, paint);

I hope this helps!

For other effects, you can use the SKShader and SKMaskFilter types. This does a blur:

path.MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, 5);

EDIT

After some time, it seems we actually have a much better way to draw text - and not just the basic underlines. I would whole-heartedly recommend this library by Brad Robinson: https://github.com/toptensoftware/RichTextKit

I mean, just look at that beautiful thing!

RichTextKit

查看更多
登录 后发表回答