How to draw rich text with Skia or SkiaSharp

Masahiko Miyasaka picture Masahiko Miyasaka · Sep 26, 2016 · Viewed 8.1k times · Source

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?

Answer

Matthew picture Matthew · Nov 4, 2016

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