A. Vreeswijk
A. Vreeswijk

Reputation: 954

How to create bitmap from string text with SkiaSharp

I created an entry where you type in a value, but now I want to create a bitmap with the text of an entry. When I got the bitmap, I can load it in SkiaSharp and use BitmapModifiers on it.

Is this possible?

Upvotes: 3

Views: 2008

Answers (1)

Jan Nepraš
Jan Nepraš

Reputation: 814

I would recommend you to go through these examples on github.

Dummy sample could look like this:

This is xaml page:

<StackLayout>
    <Entry x:Name="InputText" />
    <Button Text="Create Bitmap" Clicked="Button_Clicked" />
</StackLayout>

Codebehind:

SKBitmap helloBitmap;

void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
{
    SKImageInfo info = args.Info;
    SKSurface surface = args.Surface;
    SKCanvas canvas = surface.Canvas;

    canvas.Clear(SKColors.Aqua);

    canvas.DrawBitmap(helloBitmap, 0, 0);
}

private void Button_Clicked(object sender, EventArgs e)
{
    CreateBitmapFromText(InputText.Text);
}

private void CreateBitmapFromText(string text)
{
    // Create bitmap and draw on it
    using (SKPaint textPaint = new SKPaint { TextSize = 48 })
    {
        SKRect bounds = new SKRect();
        textPaint.MeasureText(text, ref bounds);

        helloBitmap = new SKBitmap((int)bounds.Right,
                                    (int)bounds.Height);

        using (SKCanvas bitmapCanvas = new SKCanvas(helloBitmap))
        {
            bitmapCanvas.Clear();
            bitmapCanvas.DrawText(text, 0, -bounds.Top, textPaint);
        }
    }

    SKCanvasView canvasView = new SKCanvasView();
    canvasView.PaintSurface += OnCanvasViewPaintSurface;
    Content = canvasView;
}

Upvotes: 1

Related Questions