本文主要是介绍.NET 跨平台图形库 SkiaSharp 基础应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
写在前面
SkiaSharp 是适用于 .NET 和 C# 的 2D 图形系统,由开源 Skia 图形引擎提供支持,在 Google 产品中广泛使用。 可以在应用程序中使用 SkiaSharp Xamarin.Forms 绘制 2D 矢量图形、位图和文本。支持跨平台,Windows、Linux、Anroid、IOS、WebAssembly下都可以使用,底层源码是用C++实现的。
SkiaSharp 最初由 Mono 开发,目前由 Microsoft 维护,遵循 MIT License。
SkiaSharp 图形 Xamarin.Forms - Xamarin | Microsoft Learn
在Winform中使用时,可以从NuGet 获取 SkiaSharp 类库
为了方便使用,把SKImage直接转换成Bitmap,需要再引入一个拓展类库,SkiaSharp.Views.Desktop.Common
代码实现
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);// 创建一个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){// 创建一个新的随机数生成器 var random = new Random();// 生成验证码 string code = new string(Enumerable.Repeat(chars, len).Select(s => s[random.Next(s.Length)]).ToArray());return code;}}
}
调用示例
这篇关于.NET 跨平台图形库 SkiaSharp 基础应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!