如何解决在图像 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);
}
有关更多详细信息,您可以参考 MS 文档。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/basics/text
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。