7

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?

fourpastmidnight
  • 4,032
  • 1
  • 35
  • 48
Masahiko Miyasaka
  • 171
  • 1
  • 1
  • 11

1 Answers1

20

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

Matthew
  • 4,832
  • 2
  • 29
  • 55
  • 2
    SKPaint.UnderlineText does not exist anymore. Is there a replacement? – Michael Rumpler Jul 29 '19 at 10:43
  • [This](https://github.com/google/skia/blob/81abc43e6f0b1a789e1bf116820c8ede68d778ab/gm/texteffects.cpp#L97) is an example that can be ported for your purposes. Or just draw lines below/through if you don't need to be "fancy". – Tyler Southard Dec 05 '19 at 19:04
  • Skia's API changes every month. I really admire people who are able to use this library and are willing to learn it from the source code. – Kyriet Apr 14 '23 at 22:53