SkiaSharp 是 Google's Skia 图形引擎的 .NET 版本,提供了强大的 2D 图形处理能力。本文将详细介绍如何在 WinForm 应用程序中使用 SkiaSharp 绘制各种矩形。
首先需要通过 NuGet 包管理器安装以下包:
C#using SkiaSharp;
using SkiaSharp.Views.Desktop;
namespace AppRectangle
{
public partial class Form1 : Form
{
private SKControl skControl;
public Form1()
{
InitializeComponent();
// 创建 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);
// 在这里添加绘制代码
DrawRectangles(canvas);
}
private void DrawRectangles(SKCanvas canvas)
{
// 创建画笔
using (var paint = new SKPaint())
{
// 启用防锯齿
paint.IsAntialias = true;
// 1. 绘制基础矩形
paint.Color = SKColors.Blue; // 设置颜色为蓝色
paint.Style = SKPaintStyle.Fill; // 设置填充样式
canvas.DrawRect(50, 50, 200, 100, paint);
// 2. 绘制描边矩形
paint.Color = SKColors.Red; // 设置颜色为红色
paint.Style = SKPaintStyle.Stroke; // 设置为描边样式
paint.StrokeWidth = 3; // 设置描边宽度
canvas.DrawRect(50, 200, 200, 100, paint);
// 3. 绘制圆角矩形
paint.Color = SKColors.Green; // 设置颜色为绿色
paint.Style = SKPaintStyle.Fill; // 设置填充样式
canvas.DrawRoundRect(50, 350, 200, 100, 20, 20, paint);
}
}
}
}

C#private void DrawGradientRectangle(SKCanvas canvas)
{
// 创建渐变色
using (var paint = new SKPaint())
{
// 启用防锯齿
paint.IsAntialias = true;
// 定义渐变起始点和结束点
var shader = SKShader.CreateLinearGradient(
new SKPoint(300, 50), // 起始点
new SKPoint(500, 150), // 结束点
new SKColor[] {
SKColors.Blue,
SKColors.Red
}, // 渐变颜色
null, // 颜色位置(null表示均匀分布)
SKShaderTileMode.Clamp // 渐变模式
);
paint.Shader = shader;
canvas.DrawRect(300, 50, 200, 100, paint);
// 绘制圆角矩形
canvas.DrawRoundRect(300, 200, 200, 100, 20, 20, paint);
}
}

C#private void DrawShadowRectangle(SKCanvas canvas)
{
using (var paint = new SKPaint())
{
// 启用防锯齿
paint.IsAntialias = true;
// 设置阴影效果
paint.ImageFilter = SKImageFilter.CreateDropShadow(
dx: 5, // X轴偏移
dy: 5, // Y轴偏移
sigmaX: 5, // X轴模糊程度
sigmaY: 5, // Y轴模糊程度
color: SKColors.Gray
);
paint.Color = SKColors.LightBlue;
canvas.DrawRect(300, 200, 200, 100, paint);
}
}

C#private void DrawBorderedRectangle(SKCanvas canvas)
{
// 先绘制填充
using (var fillPaint = new SKPaint())
{
fillPaint.Color = SKColors.Yellow;
fillPaint.Style = SKPaintStyle.Fill;
canvas.DrawRect(300, 150, 200, 100, fillPaint);
}
// 再绘制边框
using (var strokePaint = new SKPaint())
{
strokePaint.Color = SKColors.Orange;
strokePaint.Style = SKPaintStyle.Stroke;
strokePaint.StrokeWidth = 4;
canvas.DrawRect(300, 150, 200, 100, strokePaint);
}
}

SkiaSharp 使用的是传统的计算机图形坐标系统:
除了直接使用坐标和尺寸,还可以使用 SKRect 对象来定义矩形:
C#// 使用 SKRect 定义矩形
SKRect rect = new SKRect(50, 50, 250, 150); // left, top, right, bottom
canvas.DrawRect(rect, paint);
// 或者使用 SKRectI 用于整数坐标
SKRectI rectI = new SKRectI(50, 50, 250, 150);
SkiaSharp 提供了强大而灵活的矩形绘制功能。通过合理使用各种属性和方法,可以创建出丰富多样的矩形效果。在实际应用中,建议根据具体需求选择合适的绘制方式,并注意性能优化。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!