在Blazor中使用SkiaSharp的方法

Blazor SkiaSharp

概述

ShiaSharp是面向.NET和C#的2D图形系统,由Google产品中广泛使用的开放源代码Skia图形引擎提供支持。

可以在Blazor应用程序中使用SkiaSharp来绘制二维矢量图、位图和文字。

安装SkiaSharp包: 在Visual Studio的NuGet包管理器中搜索SkiaSharp.Views.Blazor包并将其添加到解决方案中。

image

  • Install 适用于 .NET 版本的包

image

  • SkiaSharp.Views.Blazor包会自动安装其依赖项,包含SkiaSharp核心库以及其他可能需要的库。

image

引用命名空间: 在_Imports.razor中使用using SkiaSharp语句引入。

image

画图

SKiaSharp包中主要的类

SKSurface

SKSurface 是SkiaSharp包中的一个封装了底层平台绘图表面的类。

SKSurface提供了一个画布(Canvas),允许开发者在其上执行绘图命令;
一旦绘图完成,可以通过Snapshot方法获取一个SKImage对象,从而保存或使用绘制的图像内容。

SkiaSharp.API文档中表述如下:

Represents the backend/results of drawing to a canvas.

SKCanvas

SKCanvas 是将绘图命令转换为Surface基本操作的画布的类。

SkiaSharp.API文档中表述如下:

Gets the canvas for this surface which can be used for drawing into it.

SKPaint

SKPaint 是描述绘制对象外观的类。

SkiaSharp.API文档中表述如下:

Holds the style and color information about how to draw geometries, text and bitmaps.

SKCanvasView

SKCanvasView 是显示Canvas的组件类。

public class SKCanvasView : ComponentBase, IDisposable

使用方法

@page "/"
@using SkiaSharp.Views.Blazor
<SKCanvasView
@ref = "_skiaView"
OnPaintSurface="OnPaintSurface"
IgnorePixelScaling="true"/>
@code {
private SKCanvasView _skiaView = null!;
private void OnPaintSurface(SKPaintSurfaceEventArgs e)
{
var canvas = e.Surface.Canvas;
canvas.Clear(SKColors.BlueViolet);
using var paint = new SKPaint
{
Color = SKColors.AliceBlue,
Style = SKPaintStyle.Fill
};
canvas.DrawRect(new SKRect(10, 10, 50, 50), paint);
}
}

或者,在BuildRenderTree方法中实现如下:

public class MyCanvas : ComponentBase
{
SKCanvasView _skiaView = null!;
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
base.BuildRenderTree(builder);
int sequence = 0;
builder.OpenComponent<SKCanvasView>(sequence++);
builder.AddAttribute(sequence++, "@ref", _skiaView);
builder.AddAttribute(sequence++, "OnPaintSurface", OnPaintSurface);
builder.AddAttribute(sequence++, "IgnorePixelScaling", true);
builder.CloseComponent();
}
void OnPaintSurface(SKPaintSurfaceEventArgs e)
{
var canvas = e.Surface.Canvas;
canvas.Clear(SKColors.BlueViolet);
using var paint = new SKPaint
{
Color = SKColors.AliceBlue,
Style = SKPaintStyle.Fill
};
canvas.DrawRect(new SKRect(10, 10, 50, 50), paint);
}
}

显示图形如下:

image

参考文章

  1. SkiaSharp API
    https://learn.microsoft.com/en-us/dotnet/api/skiasharp?view=skiasharp-2.88

文章声明

  • 内容准确性:我会尽力确保所分享信息的准确性和可靠性,但由于个人知识有限,难免会有疏漏或错误。如果您在阅读过程中发现任何问题,请不吝赐教,我将及时更正。

posted on   wubing7755  阅读(121)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示