2025-11-11
C#
00

目录

环境准备
基础知识
完整示例代码
注意事项
总结

SkiaSharp 是一个强大的 2D 图形库,可以用来绘制各种图形。本文将详细介绍如何使用 SkiaSharp 在 WinForms 应用程序中绘制圆形和椭圆。

环境准备

首先需要通过 NuGet 包管理器安装 SkiaSharp 相关包:

  • SkiaSharp
  • SkiaSharp.Views
  • SkiaSharp.Views.WindowsForms

基础知识

在 SkiaSharp 中:

  • 使用 SKCanvas.DrawCircle() 方法绘制圆形
  • 使用 SKCanvas.DrawOval() 方法绘制椭圆
  • 使用 SKPaint 类设置绘制样式(颜色、线宽等)

完整示例代码

C#
using SkiaSharp; using SkiaSharp.Views.Desktop; using System; using System.Windows.Forms; namespace SkiaSharpDemo { public partial class Form1 : Form { private SKControl skControl; public Form1() { InitializeComponent(); InitializeSkiaSharp(); } private void InitializeSkiaSharp() { // 创建 SKControl 控件 skControl = new SKControl(); skControl.Dock = DockStyle.Fill; skControl.PaintSurface += OnPaintSurface; this.Controls.Add(skControl); } private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e) { // 获取绘图画布 SKCanvas canvas = e.Surface.Canvas; // 清空画布(使用白色背景) canvas.Clear(SKColors.White); // 创建画笔 using (SKPaint paint = new SKPaint()) { // 设置基本属性 paint.IsAntialias = true; // 启用抗锯齿 // 1. 绘制实心红色圆形 paint.Style = SKPaintStyle.Fill; paint.Color = SKColors.Red; canvas.DrawCircle(100, 100, 50, paint); // 2. 绘制蓝色圆形边框 paint.Style = SKPaintStyle.Stroke; paint.Color = SKColors.Blue; paint.StrokeWidth = 3; canvas.DrawCircle(250, 100, 50, paint); // 3. 绘制带渐变的圆形 using (SKPaint gradientPaint = new SKPaint()) { gradientPaint.IsAntialias = true; var shader = SKShader.CreateRadialGradient( new SKPoint(400, 100), 50, new SKColor[] { SKColors.Yellow, SKColors.Red }, null, SKShaderTileMode.Clamp); gradientPaint.Shader = shader; canvas.DrawCircle(400, 100, 50, gradientPaint); } // 4. 绘制实心绿色椭圆 paint.Style = SKPaintStyle.Fill; paint.Color = SKColors.Green; paint.Shader = null; canvas.DrawOval(new SKRect(50, 200, 150, 300), paint); // 5. 绘制紫色椭圆边框 paint.Style = SKPaintStyle.Stroke; paint.Color = SKColors.Purple; paint.StrokeWidth = 2; canvas.DrawOval(new SKRect(200, 200, 300, 250), paint); // 6. 绘制虚线椭圆 paint.Style = SKPaintStyle.Stroke; paint.Color = SKColors.Orange; paint.StrokeWidth = 2; paint.PathEffect = SKPathEffect.CreateDash(new float[] { 10, 5 }, 0); canvas.DrawOval(new SKRect(350, 200, 450, 300), paint); } } } }

image.png

注意事项

  1. 记得在使用完 SKPaint 对象后进行释放
  2. 坐标系原点(0,0)在窗口左上角
  3. 使用 SKControl.Invalidate() 方法可以触发重绘
  4. 渐变和特效会占用更多资源,请适度使用

总结

SkiaSharp 提供了灵活且强大的图形绘制功能。通过合理使用 DrawCircleDrawOval 方法,配合 SKPaint 的各种属性,可以绘制出各种样式的圆形和椭圆。在实际应用中,可以根据需求组合这些基本功能,创建更复杂的图形效果。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!