Scott
Scott

Reputation: 11

I want to add text on top of a bitmap in Xamarin Forms Skia

I would like to be able to create an infographic style image in my Xamarin Forms app. I have a png that I am planning to use as the background and then add text on top of it.

I was trying to use these two links Creating and drawing on SkiaSharp bitmaps and SKCanvas.DrawText Method but I am getting an error on BitmapExtensions.

1.  Did I miss how to declare BitmapExtensions?
2.  Is this the best/easiest way to create the infographic I am trying to make?

Thank you!

       // Get text to share
       string textToShare = GamesWonText.Text + " " + GamesWon.Text + Environment.NewLine;
       textToShare += GamesLostText.Text + " " + GamesLost.Text + Environment.NewLine;
       textToShare += WinPercentText.Text + " " + WinPercent.Text + Environment.NewLine;
       textToShare += CoinsBankedText.Text + " " + CoinsBanked.Text + Environment.NewLine;
       textToShare += MaxCoinsText.Text + " " + MaxCoins.Text + Environment.NewLine;
       textToShare += AvgCoinsText.Text + " " + AvgCoins.Text + Environment.NewLine;

            // Create the image to share
            string resourceID = "Infographic Background Image.png";

            SKBitmap backgroundBitmap = BitmapExtensions.LoadBitmapResource(GetType(), resourceID);

            using (SKCanvas canvas = new SKCanvas(backgroundBitmap))
            {
                using (SKPaint paint = new SKPaint())
                {
                    paint.TextSize = 32.0f;
                    paint.IsAntialias = true;
                    paint.Color = new SKColor(0, 0, 0);
                    paint.IsStroke = false;

                    canvas.DrawText(textToShare, 540f, 960f, paint);
                }
            }

UPDATE TO INCLUDE COMMMENT

The error I am getting is "CS0103: The name 'BitmapExtensions' does not exist in the current context.

Upvotes: 1

Views: 638

Answers (1)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

The BitmapExtensions is a class. You could use the code below.

 static class BitmapExtensions
{
    public static SKBitmap LoadBitmapResource(Type type, string resourceID)
    {
        Assembly assembly = type.GetTypeInfo().Assembly;

        using (Stream stream = assembly.GetManifestResourceStream(resourceID))
        {
            return SKBitmap.Decode(stream);
        }
    }

}

For more details, you could check the sample code in the link below. https://github.com/xamarin/xamarin-forms-samples/blob/main/SkiaSharpForms/Demos/Demos/SkiaSharpFormsDemos/BitmapExtensions.cs

Upvotes: 1

Related Questions