Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created May 15, 2019 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/336cea8fbbfd7fb34a8b85968840084a to your computer and use it in GitHub Desktop.
Save guitarrapc/336cea8fbbfd7fb34a8b85968840084a to your computer and use it in GitHub Desktop.
Draw text to png file generated by SkiaSharp. https://github.com/mono/SkiaSharp
void Main()
{
DrawTextToPng("Hogemoge-fugaf@-!!!$&'&piyo_-=hiogfew", 10);
}
public void DrawTextToPng(string text, int xPadding = 0)
{
// draw some text
var paint = new SKPaint
{
Color = SKColors.White,
IsAntialias = true,
Style = SKPaintStyle.Fill,
TextAlign = SKTextAlign.Center,
TextSize = 24
};
var width = paint.MeasureText(text);
var info = new SKImageInfo((int)width + xPadding, 50);
using (var surface = SKSurface.Create(info))
{
var canvas = surface.Canvas;
// make sure the canvas is blank
canvas.Clear(SKColors.Black);
var coord = new SKPoint(info.Width / 2, (info.Height + paint.TextSize) / 2);
canvas.DrawText(text, coord, paint);
// save the file
using (var image = surface.Snapshot())
using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
using (var stream = File.OpenWrite("output.png"))
{
data.SaveTo(stream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment