Write text on an image Xamarin android

Viewed 749

I want to write text on an image then save it, but my code has runtime error.

error : System.PlatformNotSupportedException: 'Operation is not supported on this platform.'

using System.Drawing;
    
    
 public void Watermark(string picturePath, string text)
         {
    
             PointF firstLocation = new PointF(10f, 10f);
             PointF secondLocation = new PointF(10f, 50f);
    
             Bitmap bitmap = (Bitmap)Image.FromFile(picturePath);//load the image file
    
             using (Graphics graphics = Graphics.FromImage(bitmap))
             {
                 using (Font arialFont = new Font("Arial", 10))
                 {
                     graphics.DrawString(text, arialFont, Brushes.Blue, firstLocation);
                 }
             }
    
             bitmap.Save(picturePath);
         }
1 Answers

Xamarin provides the SkiaSharp to integrate Text and Graphics.

The SKCanvas.DrawText could be used to draw the text.

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

        canvas.Clear();

        string str = "Hello SkiaSharp!";

        // Create an SKPaint object to display the text
        SKPaint textPaint = new SKPaint
        {
            Color = SKColors.Chocolate
        };

        // Adjust TextSize property so text is 90% of screen width
        float textWidth = textPaint.MeasureText(str);
        textPaint.TextSize = 0.9f * info.Width * textPaint.TextSize / textWidth;

        // Find the text bounds
        SKRect textBounds = new SKRect();
        textPaint.MeasureText(str, ref textBounds);

        // Calculate offsets to center the text on the screen
        float xText = info.Width / 2 - textBounds.MidX;
        float yText = info.Height / 2 - textBounds.MidY;

        // And draw the text
        canvas.DrawText(str, xText, yText, textPaint);

        // Create a new SKRect object for the frame around the text
        SKRect frameRect = textBounds;
        frameRect.Offset(xText, yText);
        frameRect.Inflate(10, 10);

        // Create an SKPaint object to display the frame
        SKPaint framePaint = new SKPaint
        {
            Style = SKPaintStyle.Stroke,
            StrokeWidth = 5,
            Color = SKColors.Blue
        };

        // Draw one frame
        canvas.DrawRoundRect(frameRect, 20, 20, framePaint);

        // Inflate the frameRect and draw another
        frameRect.Inflate(10, 10);
        framePaint.Color = SKColors.DarkBlue;
        canvas.DrawRoundRect(frameRect, 30, 30, framePaint);
    }

enter image description here

For more details, you could refer to the MS docs. https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/basics/text

Related