Skip to content

A Winform-liked cross-platform TextRenderer implemented with SkiaSharp

License

Notifications You must be signed in to change notification settings

ryancheung/SkiaTextRenderer

Repository files navigation

Nuget

A Winform-liked TextRenderer implemented with SkiaSharp

SkiaTextRenderer is a text renderer that simulate the System.Windows.Forms.TextRenderer.

Its goal is to provider a cross-platform TextRenderer that can be easly used in game or app.

The APIs are just like the Winform version. Even TextFormatFlags was directly copied and used. Most of the flags are implemented for now, left flags could be implemented later.

Examples

TextFormatFlags.Default

TextFormatFlags.Default

TextFormatFlags.HorizontalCenter

TextFormatFlags.HorizontalCenter

TextFormatFlags.LeftAndRightPadding

TextFormatFlags.LeftAndRightPadding

TextFormatFlags.NoPadding

TextFormatFlags.NoPadding

Italic & TextFormatFlags.Default

Italic & TextFormatFlags.Default

Underline & TextFormatFlags.Default

Underline & TextFormatFlags.Default

StrikeThrough & TextFormatFlags.Default

StrikeThrough & TextFormatFlags.Default

Sized & TextFormatFlags.Default

Sized & TextFormatFlags.Default

Sized & TextFormatFlags.VertialCenter

Sized & TextFormatFlags.VertialCenter & TextFormatFlags.WordBreak

Sized & TextFormatFlags.VertialCenter & TextFormatFlags.WordBreak

Sized & TextFormatFlags.VertialCenter & TextFormatFlags.WordBreak

Sized & TextFormatFlags.HorizontalCenter & TextFormatFlags.VerticalCenter & TextFormatFlags.WordBreak

Sized & TextFormatFlags.HorizontalCenter & TextFormatFlags.VerticalCenter & TextFormatFlags.WordBreak

Auto break line with newline character '\n' or '\r' or "\r\n"

Auto break line with newline character '\n' or '\r' or "\r\n"

Install

nuget install SkiaTextRenderer

Usage

note TextRenderer class is deprecated and will be removed in v2.1.0, please use the new TextRendererSk instead.

static void TestDraw(string text, Font font, TextFormatFlags flags)
{
    var size = TextRendererSk.MeasureText(text, font, 0, flags);
    var BackColour = SKColors.Black;

    using (SKBitmap bitmap = new SKBitmap(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Unpremul))
    using (var canvas = new SKCanvas(bitmap))
    {
        canvas.Clear(BackColour);

        TextRendererSk.DrawText(canvas, text, font, new Rectangle(0, 0, size.Width, size.Height), SKColors.White, flags);

        using (Stream s = File.Open(fileName, FileMode.Create))
        {
            SKData d = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
            d.SaveTo(s);
        }
    }
}

TODO

  • Implement TextFormatFlags.WordEllipsis
  • Support long text drawing with offset defined by cursor position