在图像 Xamarin android 上写入文本

问题描述

我想在图像上写入文本然后保存它,但我的代码有运行时错误

错误System.PlatformNotSupportedException:“此平台不支持操作。”

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);
         }

解决方法

Xamarin 提供了 SkiaSharp 来集成文本和图形。

SKCanvas.DrawText 可用于绘制文本。

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,framePaint);

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

enter image description here

有关更多详细信息,您可以参考 MS 文档。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/basics/text