寫在前面
SkiaSharp 是適用于 .NET 和 C# 的 2D 圖形系統(tǒng),由開源 Skia 圖形引擎提供支持,在 Google 產品中廣泛使用。 可以在應用程序中使用 SkiaSharp Xamarin.Forms 繪制 2D 矢量圖形、位圖和文本。支持跨平臺,Windows、Linux、Anroid、IOS、WebAssembly下都可以使用,底層源碼是用C++實現(xiàn)的。
SkiaSharp 最初由 Mono 開發(fā),目前由 Microsoft 維護,遵循 MIT License。
?SkiaSharp 圖形 Xamarin.Forms - Xamarin | Microsoft Learn
在Winform中使用時,可以從NuGet 獲取?SkiaSharp 類庫
為了方便使用,把SKImage直接轉換成Bitmap,需要再引入一個拓展類庫,SkiaSharp.Views.Desktop.Common
?
代碼實現(xiàn)
using SkiaSharp;
using SkiaSharp.Views.Desktop;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SkiaSharpDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
//圖片寬度
var width = 128;
//圖片高度
var height = 36;
//生成隨機驗證碼
var code = CreateValidateCode(4);
// 創(chuàng)建一個SkiaSharp畫布
using (var surface = SKSurface.Create(new SKImageInfo(width, height)))
{
var canvas = surface.Canvas;
// 清除畫布
canvas.Clear(SKColors.White);
// 使用SkiaSharp繪制驗證碼文本
using (var textPaint = new SKPaint())
{
textPaint.Color = SKColors.Black;
textPaint.IsAntialias = true;
textPaint.TextSize = height * 0.8f; // 設置文本大小
textPaint.StrokeWidth = 3;
var textBounds = new SKRect();
textPaint.MeasureText(code, ref textBounds);
var xText = (width - textBounds.Width) / 2;
var yText = (height - textBounds.Height) / 2 - textBounds.Top;
canvas.RotateDegrees(-5, 0, 0); // 加一點點旋轉角度
canvas.DrawText(code, xText, yText, textPaint);
}
// 繪制干擾線
using (var linePaint = new SKPaint())
{
// 半透明藍色
linePaint.Color = new SKColor(0, 0, 255, 128);
linePaint.StrokeWidth = 2;
linePaint.IsAntialias = true;
var random = new Random();
for (int i = 0; i < 8; i++) // 繪制5條干擾線
{
float x1 = 0;
float y1 = random.Next(height);
float x2 = width;
float y2 = random.Next(height);
canvas.DrawLine(x1, y1, x2, y2, linePaint);
}
}
// 保存圖像到文件
using (var image = surface.Snapshot())
{
picTarget.Image = image.ToBitmap();
}
}
}
// 可選字符集
private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private string CreateValidateCode(int len)
{
// 創(chuàng)建一個新的隨機數(shù)生成器
var random = new Random();
// 生成驗證碼
string code = new string(Enumerable.Repeat(chars, len)
.Select(s => s[random.Next(s.Length)]).ToArray());
return code;
}
}
}
調用示例
文章來源:http://www.zghlxwxcb.cn/news/detail-824437.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-824437.html
到了這里,關于.NET 跨平臺圖形庫 SkiaSharp 基礎應用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!