Data visualization is a critical component of modern web applications, enabling users to interpret complex information quickly through charts and graphs. SkiaSharp, a versatile 2D graphics library, empowers ASP.NET Core developers to create dynamic, high-quality charts and graphs that enhance user experience. In 2025, as web applications demand interactive and visually appealing data displays, SkiaSharp offers a robust solution for rendering custom graphics server-side or client-side. This comprehensive guide explores how to leverage SkiaSharp in ASP.NET Core to build dynamic charts and graphs, providing step-by-step instructions, practical examples, and best practices.

This article is designed for ASP.NET Core developers of all levels, from beginners to seasoned professionals, and is written in clear, engaging language suitable for a 10th-grade audience. We’ll cover SkiaSharp setup, chart creation, interactivity, performance optimization, and real-world applications. By the end, you’ll be equipped to create stunning, dynamic visualizations that captivate users.

“SkiaSharp transforms ASP.NET Core applications with dynamic, cross-platform charts and graphs.”

Understanding SkiaSharp and Its Role in ASP.NET Core

SkiaSharp is an open-source, cross-platform 2D graphics library built on Google’s Skia graphics engine. It provides a powerful API for rendering shapes, text, images, and animations in .NET applications. In ASP.NET Core, SkiaSharp enables developers to generate server-side or client-side graphics, making it ideal for creating dynamic charts and graphs.

Why Use SkiaSharp for Charts and Graphs?

Charts and graphs require precise rendering of shapes, text, and data-driven visuals. SkiaSharp excels in this area due to its flexibility, hardware-accelerated rendering, and compatibility with ASP.NET Core’s server-side and client-side capabilities. Unlike traditional charting libraries, SkiaSharp allows complete customization, enabling developers to tailor visuals to specific needs.

Key benefits of SkiaSharp include:

  • Customizable Graphics: Draw unique charts with full control over appearance.
  • Cross-Platform Support: Render graphics consistently across environments.
  • Performance: Leverage hardware acceleration for fast rendering.
  • Flexibility: Generate graphics server-side or client-side in ASP.NET Core.

SkiaSharp in the ASP.NET Core Ecosystem

ASP.NET Core is a versatile framework for building modern web applications, supporting server-side rendering, APIs, and client-side frameworks like Blazor. SkiaSharp integrates seamlessly, allowing developers to create charts for web pages, APIs, or Blazor components. This makes it a top choice for data-driven applications in 2025.

“SkiaSharp’s flexibility makes it a game-changer for creating custom charts in ASP.NET Core.”

Setting Up SkiaSharp in an ASP.NET Core Project

To create dynamic charts and graphs, you need to set up SkiaSharp in your ASP.NET Core project. This section provides a step-by-step guide to get started.

Creating an ASP.NET Core Project

Open Visual Studio 2022 or later and select the “ASP.NET Core Web App” template for MVC, Razor Pages, or Blazor, depending on your needs. Name your project (e.g., “ChartApp”) and choose a save location. This creates a web application ready for SkiaSharp integration.

For this guide, we’ll use a Razor Pages project, but the concepts apply to MVC or Blazor.

Installing SkiaSharp NuGet Packages

SkiaSharp requires specific NuGet packages for ASP.NET Core:

  • SkiaSharp: Core library for graphics rendering.
  • SkiaSharp.Views.Blazor (optional for Blazor projects).

In Visual Studio, open the NuGet Package Manager and install SkiaSharp:

<PackageReference Include="SkiaSharp" Version="2.88.8" />

For Blazor, add:

<PackageReference Include="SkiaSharp.Views.Blazor" Version="2.88.8" />

Configuring SkiaSharp for Rendering

Unlike .NET MAUI, ASP.NET Core doesn’t require specific initialization for SkiaSharp, as it’s used directly in controllers, Razor Pages, or Blazor components. For server-side rendering, you’ll create images in memory and serve them as streams. For client-side rendering (e.g., Blazor), use SKCanvasView in a Blazor component.

Adding a Drawing Surface for Blazor

For Blazor projects, add an SKCanvasView to a component. Create a Razor component (e.g., Chart.razor):

@using SkiaSharp.Views.Blazor<SKCanvasView @ref="canvasView" OnPaintSurface="OnPaintSurface" Width="500" Height="300" />

In the code-behind (Chart.razor.cs):

public partial class Chart{    private SKCanvasView canvasView;    private void OnPaintSurface(SKPaintSurfaceEventArgs e)    {        SKCanvas canvas = e.Surface.Canvas;        canvas.Clear(SKColors.White);        // Add chart drawing logic here    }}

For server-side rendering, we’ll cover generating images in the next section.

Rendering Basic Charts with SkiaSharp

SkiaSharp’s SKCanvas is the foundation for rendering charts and graphs. This section covers creating a simple bar chart server-side and client-side.

Server-Side Bar Chart

Server-side rendering generates chart images in a controller or Razor Page and serves them as streams. Create a controller action to generate a bar chart.

Example in ChartsController.cs:

using Microsoft.AspNetCore.Mvc;using SkiaSharp;namespace ChartApp.Controllers;public class ChartsController : Controller{    public IActionResult BarChart()    {        var data = new float[] { 50, 75, 30, 90, 60 };        using var bitmap = new SKBitmap(500, 300);        using var canvas = new SKCanvas(bitmap);        canvas.Clear(SKColors.White);        float barWidth = 500f / data.Length;        float maxValue = data.Max();        for (int i = 0; i < data.Length; i++)        {            float height = (data[i] / maxValue) * 250;            var rect = new SKRect(i * barWidth, 300 - height, (i + 1) * barWidth, 300);            using var paint = new SKPaint { Color = SKColors.Blue, Style = SKPaintStyle.Fill };            canvas.DrawRect(rect, paint);        }        using var stream = new MemoryStream();        bitmap.Encode(stream, SKEncodedImageFormat.Png, 100);        stream.Position = 0;        return File(stream, "image/png");    }}

In a Razor view (BarChart.cshtml):

<img src="/Charts/BarChart" alt="Dynamic Bar Chart" />

This renders a bar chart as a PNG image.

Client-Side Bar Chart in Blazor

For client-side rendering, use SKCanvasView in a Blazor component.

Example in BarChart.razor:

@using SkiaSharp@using SkiaSharp.Views.Blazor<SKCanvasView @ref="canvasView" OnPaintSurface="OnPaintSurface" Width="500" Height="300" />@code {    private SKCanvasView canvasView;    private float[] data = new float[] { 50, 75, 30, 90, 60 };    private void OnPaintSurface(SKPaintSurfaceEventArgs e)    {        SKCanvas canvas = e.Surface.Canvas;        canvas.Clear(SKColors.White);        float barWidth = e.Info.Width / (float)data.Length;        float maxValue = data.Max();        for (int i = 0; i < data.Length; i++)        {            float height = (data[i] / maxValue) * e.Info.Height * 0.8f;            var rect = new SKRect(i * barWidth, e.Info.Height - height, (i + 1) * barWidth, e.Info.Height);            using var paint = new SKPaint { Color = SKColors.Green, Style = SKPaintStyle.Fill };            canvas.DrawRect(rect, paint);        }    }}

This renders a bar chart client-side in Blazor.

“SkiaSharp’s canvas makes creating dynamic bar charts in ASP.NET Core simple and flexible.”

Building Dynamic Chart Types

SkiaSharp supports various chart types, such as line charts, pie charts, and area charts. This section demonstrates creating a dynamic pie chart and adding interactivity.

Creating a Pie Chart

A pie chart visualizes proportions. Here’s an example of a server-side pie chart:

public IActionResult PieChart(){    var data = new float[] { 30, 20, 25, 15, 10 };    var colors = new SKColor[] { SKColors.Red, SKColors.Blue, SKColors.Green, SKColors.Yellow, SKColors.Purple };    using var bitmap = new SKBitmap(500, 500);    using var canvas = new SKCanvas(bitmap);    canvas.Clear(SKColors.White);    float total = data.Sum();    float startAngle = 0;    for (int i = 0; i < data.Length; i++)    {        float sweepAngle = (data[i] / total) * 360;        using var paint = new SKPaint { Color = colors[i], Style = SKPaintStyle.Fill };        canvas.DrawArc(new SKRect(50, 50, 450, 450), startAngle, sweepAngle, true, paint);        startAngle += sweepAngle;    }    using var stream = new MemoryStream();    bitmap.Encode(stream, SKEncodedImageFormat.Png, 100);    stream.Position = 0;    return File(stream, "image/png");}

In a Razor view:

<img src="/Charts/PieChart" alt="Dynamic Pie Chart" />

Adding Labels to the Pie Chart

Add labels to display data values:

for (int i = 0; i < data.Length; i++){    float sweepAngle = (data[i] / total) * 360;    float angle = startAngle + sweepAngle / 2;    float rad = angle * (float)Math.PI / 180;    float x = 250 + (float)Math.Cos(rad) * 150;    float y = 250 + (float)Math.Sin(rad) * 150;    using var textPaint = new SKPaint { TextSize = 16, Color = SKColors.Black };    canvas.DrawText($"{data[i]}%", x, y, textPaint);    startAngle += sweepAngle;}

This places percentage labels on each pie slice.

Making Charts Interactive

For client-side interactivity in Blazor, add mouse or touch events to highlight chart segments. Modify the Blazor pie chart:

<SKCanvasView @ref="canvasView" OnPaintSurface="OnPaintSurface" Width="500" Height="500" OnMouseMove="OnMouseMove" />@code {    private SKCanvasView canvasView;    private float[] data = new float[] { 30, 20, 25, 15, 10 };    private SKColor[] colors = new SKColor[] { SKColors.Red, SKColors.Blue, SKColors.Green, SKColors.Yellow, SKColors.Purple };    private int highlightedIndex = -1;    private void OnPaintSurface(SKPaintSurfaceEventArgs e)    {        SKCanvas canvas = e.Surface.Canvas;        canvas.Clear(SKColors.White);        float total = data.Sum();        float startAngle = 0;        for (int i = 0; i < data.Length; i++)        {            float sweepAngle = (data[i] / total) * 360;            using var paint = new SKPaint            {                Color = colors[i],                Style = SKPaintStyle.Fill,                IsAntialias = true            };            if (i == highlightedIndex) paint.Color = colors[i].WithAlpha(200);            canvas.DrawArc(new SKRect(50, 50, 450, 450), startAngle, sweepAngle, true, paint);            startAngle += sweepAngle;        }    }    private void OnMouseMove(SKMouseEventArgs e)    {        float x = e.Location.X - 250;        float y = e.Location.Y - 250;        float angle = (float)Math.Atan2(y, x) * 180 / (float)Math.PI;        if (angle < 0) angle += 360;        float total = data.Sum();        float currentAngle = 0;        highlightedIndex = -1;        for (int i = 0; i < data.Length; i++)        {            float sweepAngle = (data[i] / total) * 360;            if (angle >= currentAngle && angle < currentAngle + sweepAngle)            {                highlightedIndex = i;                break;            }            currentAngle += sweepAngle;        }        canvasView.InvalidateSurface();    }}

This highlights pie slices on mouse hover.

“Interactive charts with SkiaSharp engage users by responding to input in real time.”

Creating Custom Chart Components

Custom components encapsulate chart logic for reuse. This section builds a reusable bar chart component for Blazor.

Defining the Bar Chart Component

Create BarChart.razor:

@using SkiaSharp@using SkiaSharp.Views.Blazor<SKCanvasView @ref="canvasView" OnPaintSurface="OnPaintSurface" Width="@Width" Height="@Height" />@code {    [Parameter]    public List<float> Data { get; set; } = new List<float>();    [Parameter]    public int Width { get; set; } = 500;    [Parameter]    public int Height { get; set; } = 300;    [Parameter]    public Color BarColor { get; set; } = Colors.Blue;    private SKCanvasView canvasView;    private void OnPaintSurface(SKPaintSurfaceEventArgs e)    {        SKCanvas canvas = e.Surface.Canvas;        canvas.Clear(SKColors.White);        if (Data.Any())        {            float barWidth = e.Info.Width / (float)Data.Count;            float maxValue = Data.Max();            for (int i = 0; i < Data.Count; i++)            {                float height = (Data[i] / maxValue) * e.Info.Height * 0.8f;                var rect = new SKRect(i * barWidth, e.Info.Height - height, (i + 1) * barWidth, e.Info.Height);                using var paint = new SKPaint { Color = BarColor.ToSKColor(), Style = SKPaintStyle.Fill };                canvas.DrawRect(rect, paint);            }        }    }}

Use the component in another page:

<BarChart Data="@(new List<float> { 50, 75, 30, 90, 60 })" Width="600" Height="400" BarColor="Green" />

This creates a reusable bar chart component.

Adding Axes and Labels

Enhance the bar chart with axes and labels:

private void OnPaintSurface(SKPaintSurfaceEventArgs e){    SKCanvas canvas = e.Surface.Canvas;    canvas.Clear(SKColors.White);    if (Data.Any())    {        float barWidth = e.Info.Width / (float)Data.Count;        float maxValue = Data.Max();        // Draw Y-axis        using var axisPaint = new SKPaint { Color = SKColors.Black, Style = SKPaintStyle.Stroke, StrokeWidth = 2 };        canvas.DrawLine(50, 50, 50, e.Info.Height - 50, axisPaint);        // Draw X-axis        canvas.DrawLine(50, e.Info.Height - 50, e.Info.Width - 50, e.Info.Height - 50, axisPaint);        // Draw bars and labels        for (int i = 0; i < Data.Count; i++)        {            float height = (Data[i] / maxValue) * (e.Info.Height - 100);            var rect = new SKRect(50 + i * barWidth, e.Info.Height - 50 - height, 50 + (i + 1) * barWidth, e.Info.Height - 50);            using var barPaint = new SKPaint { Color = BarColor.ToSKColor(), Style = SKPaintStyle.Fill };            canvas.DrawRect(rect, barPaint);            using var textPaint = new SKPaint { TextSize = 14, Color = SKColors.Black };            canvas.DrawText($"{Data[i]}", 50 + i * barWidth + barWidth / 2, e.Info.Height - 30, textPaint);        }    }}

This adds axes and data labels for clarity.

Adding Animations to Charts

Animations make charts more engaging. This section adds a growing animation to the bar chart.

Example in BarChart.razor.cs:

private float animationProgress = 0;protected override async Task OnAfterRenderAsync(bool firstRender){    if (firstRender)    {        while (animationProgress < 1)        {            animationProgress += 0.02f;            canvasView.InvalidateSurface();            await Task.Delay(16);        }    }}private void OnPaintSurface(SKPaintSurfaceEventArgs e){    SKCanvas canvas = e.Surface.Canvas;    canvas.Clear(SKColors.White);    if (Data.Any())    {        float barWidth = e.Info.Width / (float)Data.Count;        float maxValue = Data.Max();        for (int i = 0; i < Data.Count; i++)        {            float height = (Data[i] / maxValue) * e.Info.Height * 0.8f * animationProgress;            var rect = new SKRect(i * barWidth, e.Info.Height - height, (i + 1) * barWidth, e.Info.Height);            using var paint = new SKPaint { Color = BarColor.ToSKColor(), Style = SKPaintStyle.Fill };            canvas.DrawRect(rect, paint);        }    }}

This animates bars growing from the bottom up.

“Animations with SkiaSharp make charts come alive, enhancing user engagement.”

Optimizing Chart Performance

To ensure high-performance charts in ASP.NET Core:

  • Cache Bitmaps: Store static chart elements in SKBitmap objects.
  • Minimize Redraws: Only invalidate the canvas when data changes.
  • Simplify Graphics: Avoid overly complex shapes or paths.
  • Optimize Server-Side Rendering: Use memory-efficient streams for image generation.

Example of caching:

private static readonly SKBitmap cachedBackground = new SKBitmap(500, 300);public IActionResult CachedBarChart(){    if (cachedBackground.Pixels.Length == 0)    {        using var canvas = new SKCanvas(cachedBackground);        canvas.Clear(SKColors.White);        // Draw static background elements    }    // Draw dynamic data}

Comparing SkiaSharp with Other Charting Libraries

SkiaSharpYesNativeHighHigh
Chart.jsYesVia JavaScriptModerateModerate
SyncfusionYesNativeHighHigh
OxyPlotYesNativeModerateModerate

SkiaSharp’s high customization and .NET integration make it ideal for bespoke charts.

Real-World Applications

SkiaSharp powers charts in various ASP.NET Core applications:

  • Business Dashboards: Display sales or performance metrics.
  • Financial Apps: Render stock or budget charts.
  • Educational Tools: Visualize data for learning platforms.
  • Health Apps: Show fitness or medical data trends.

For example, a retail app might use SkiaSharp to create dynamic sales charts, while a finance app could render real-time stock graphs.

Best Practices for SkiaSharp Charts

Follow these guidelines:

  • Enable Anti-Aliasing: Use IsAntialias = true for smooth visuals.
  • Handle Scaling: Adjust for device resolution with e.Info.PixelsPerInch.
  • Dispose Resources: Use using statements for SKPaint and SKBitmap.
  • Test Across Browsers: Ensure compatibility in Blazor or server-side rendering.

Avoid pitfalls like neglecting canvas invalidation or overloading server-side resources.

Conclusion

This guide has explored how to create dynamic charts and graphs in ASP.NET Core using SkiaSharp. We covered setup, rendering bar and pie charts, adding interactivity and animations, building custom components, and optimizing performance. Real-world applications and comparisons highlight SkiaSharp’s strengths for data visualization in 2025.

Key takeaways include:

  • Flexible Rendering: SkiaSharp supports server-side and client-side chart creation.
  • Dynamic Visuals: Build interactive, animated charts with ease.
  • Custom Components: Create reusable chart controls for consistent designs.
  • Performance Optimization: Cache and minimize redraws for smooth rendering.

SkiaSharp is a powerful tool for ASP.NET Core developers seeking to create dynamic, high-quality charts. Experiment with the examples, explore advanced features, and enhance your web applications with stunning data visualizations.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top