SkiaSharp is a powerful 2D graphics library that can be used to draw various shapes. This article will provide a detailed introduction on how to use SkiaSharp to draw circles and ellipses in WinForms applications.
First, you need to install SkiaSharp related packages through NuGet Package Manager:
In SkiaSharp:
SKCanvas.DrawCircle() method to draw circlesSKCanvas.DrawOval() method to draw ellipsesSKPaint class to set drawing styles (color, line width, etc.)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()
{
// Create SKControl control
skControl = new SKControl();
skControl.Dock = DockStyle.Fill;
skControl.PaintSurface += OnPaintSurface;
this.Controls.Add(skControl);
}
private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
// Get drawing canvas
SKCanvas canvas = e.Surface.Canvas;
// Clear canvas (using white background)
canvas.Clear(SKColors.White);
// Create paint brush
using (SKPaint paint = new SKPaint())
{
// Set basic properties
paint.IsAntialias = true; // Enable anti-aliasing
// 1. Draw solid red circle
paint.Style = SKPaintStyle.Fill;
paint.Color = SKColors.Red;
canvas.DrawCircle(100, 100, 50, paint);
// 2. Draw blue circle border
paint.Style = SKPaintStyle.Stroke;
paint.Color = SKColors.Blue;
paint.StrokeWidth = 3;
canvas.DrawCircle(250, 100, 50, paint);
// 3. Draw gradient circle
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. Draw solid green ellipse
paint.Style = SKPaintStyle.Fill;
paint.Color = SKColors.Green;
paint.Shader = null;
canvas.DrawOval(new SKRect(50, 200, 150, 300), paint);
// 5. Draw purple ellipse border
paint.Style = SKPaintStyle.Stroke;
paint.Color = SKColors.Purple;
paint.StrokeWidth = 2;
canvas.DrawOval(new SKRect(200, 200, 300, 250), paint);
// 6. Draw dashed ellipse
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);
}
}
}
}

SKPaint objects after useSKControl.Invalidate() method to trigger redrawingSkiaSharp provides flexible and powerful graphics drawing capabilities. By properly using DrawCircle and DrawOval methods, combined with various properties of SKPaint, you can draw circles and ellipses with various styles. In practical applications, you can combine these basic functions according to your needs to create more complex graphics effects.
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!