|
| 1 | +--- |
| 2 | +title: "Generating a Hexagonal Grid with SkiaSharp in C#" |
| 3 | +author: "PrashantUnity" |
| 4 | +weight: 102 |
| 5 | +date: 2024-08-03 |
| 6 | +lastmod: 2024-08-03 |
| 7 | +dateString: August 2024 |
| 8 | +description: "This guide explains how to generate a hexagonal grid using the SkiaSharp library in C#. It covers the basic concepts of hexagon geometry, provides functions to calculate hexagon points from a single coordinate, and demonstrates how to draw a complete hexagonal grid on a canvas. The tutorial includes code snippets and explanations to ensure the implementation is easily understandable and modifiable by reader." |
| 9 | +#canonicalURL: "https://canonical.url/to/page" |
| 10 | +cover: |
| 11 | + image: "cover.jpg" # image path/url |
| 12 | + alt: "Generate Thumbnail" # alt text |
| 13 | + #caption: "Optical Character Recognition" display caption under cover |
| 14 | + |
| 15 | +tags: [ "CSharp", "SkiaSharp","Hexagon","Hexagonal Grid"] |
| 16 | +keywords: [ "NET", "codefrydev", "C sharp", "CFD", "SkiaSharp","Hexagon","Hexagonal Grid","Skia"] |
| 17 | +--- |
| 18 | + |
| 19 | + |
| 20 | +## Concept |
| 21 | + |
| 22 | +- A hexagon consists of six vertices. |
| 23 | +- Given one vertex coordinate, we can find all other vertices as the angle between two edges is 120 degrees. |
| 24 | +- Consider a starting point **(x, y)** and the width of an edge **b**. |
| 25 | +- The right neighbor points will be **(x + b, y)**. |
| 26 | +- The right neighbor of the right neighbor will be **(x + b + b * Cos(60), y + b * Sin(60))** and so on. |
| 27 | + |
| 28 | +### Example |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | +## Code Implementation |
| 33 | + |
| 34 | +### SkiaSharp Setup |
| 35 | + |
| 36 | +- Refer to the [SkiaSharp setup guide]({{< relref "blog/skiasharp/basic.md" >}}) |
| 37 | + |
| 38 | +### Importing Skiasharp Library |
| 39 | + |
| 40 | +```csharp |
| 41 | +#r "nuget:SkiaSharp" |
| 42 | +``` |
| 43 | + |
| 44 | +### Importing name space |
| 45 | + |
| 46 | +```csharp |
| 47 | +using SkiaSharp; |
| 48 | +using System.Collections.Generic; |
| 49 | + |
| 50 | +``` |
| 51 | + |
| 52 | +### Function to Get Hexagon Points from a Single Coordinate |
| 53 | + |
| 54 | +```csharp |
| 55 | +SKPoint[] GetPoints(float x, float y,float width) |
| 56 | +{ |
| 57 | + var ls = new List<SKPoint>(); |
| 58 | + |
| 59 | + ls.Add(new SKPoint(x ,y)); |
| 60 | + ls.Add(new SKPoint(x + width ,y)); |
| 61 | + ls.Add(new SKPoint(x + width +width/2,y + width*MathF.Sqrt(3)/2)); |
| 62 | + ls.Add(new SKPoint(x + width ,y + width*MathF.Sqrt(3))); |
| 63 | + ls.Add(new SKPoint(x ,y + width*MathF.Sqrt(3))); |
| 64 | + ls.Add(new SKPoint(x - width/2 ,y + width*MathF.Sqrt(3)/2)); |
| 65 | + ls.Add(new SKPoint(x,y)); |
| 66 | + return ls.ToArray(); |
| 67 | +} |
| 68 | +``` |
| 69 | + |
| 70 | +## Function to Get Next Starting Point |
| 71 | + |
| 72 | +```csharp |
| 73 | +(float,float) GetNextPoint(float x, float y, float width) |
| 74 | +{ |
| 75 | + return (x + width +width/2,y + width*MathF.Sqrt(3)/2); |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +- This function calculates the next starting coordinate from **(x, y)**. |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | +- So we will have two starting point |
| 84 | +- both will come alternatively |
| 85 | +- Below Code Generate the possible points |
| 86 | + |
| 87 | +```csharp |
| 88 | +int width = 1200; |
| 89 | +int height = 750; |
| 90 | +int step =60; |
| 91 | +SKBitmap bmp = new(width, height); |
| 92 | +SKCanvas canvas = new(bmp); |
| 93 | + |
| 94 | +canvas.Clear(SKColor.Parse("#fff")); |
| 95 | + |
| 96 | +Random rand = new(0); |
| 97 | +SKPaint paint = new() |
| 98 | +{ |
| 99 | + Color = SKColors.White.WithAlpha(100), |
| 100 | + IsAntialias = true , |
| 101 | + StrokeWidth = 4, |
| 102 | + ColorF = SKColor.Parse("#003366"), |
| 103 | + Style = SKPaintStyle.Stroke |
| 104 | +}; |
| 105 | + var ls = GetPoints(width/5,height/3,200); |
| 106 | +var skpath = new SKPath(); |
| 107 | +skpath.AddPoly(ls); |
| 108 | +canvas.DrawPath(skpath,paint); |
| 109 | + |
| 110 | +paint.TextSize = 48f; |
| 111 | +canvas.DrawText($"(x,y)",ls[0],paint); |
| 112 | +canvas.DrawText($"(x + (w)*3/2, y + (w)*sqrt(3)/2)",ls[2],paint); |
| 113 | + |
| 114 | +canvas.DrawText($"(x + (w)*3/2, y + 0)",(ls[0].X +200*(3.0f/2)),ls[0].Y,paint); |
| 115 | + |
| 116 | +bmp.Display(); |
| 117 | + |
| 118 | +``` |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | +## final Code |
| 123 | + |
| 124 | +- I am Drawing hexagonal Shape in vertically fashion |
| 125 | +- Line number 22 that is while loop is for width of image Horizontaly |
| 126 | +- Line number 37 for vertically for height |
| 127 | + |
| 128 | +- Line Number 25 to 36 will deside next verticall starting cordinate points. |
| 129 | + |
| 130 | +```csharp |
| 131 | +int width = 1200; |
| 132 | +int height = 750; |
| 133 | +int step = 60; |
| 134 | +SKBitmap bmp = new(width, height); |
| 135 | +SKCanvas canvas = new(bmp); |
| 136 | + |
| 137 | +canvas.Clear(SKColor.Parse("#fff")); |
| 138 | + |
| 139 | +SKPaint paint = new() |
| 140 | +{ |
| 141 | + IsAntialias = true, |
| 142 | + StrokeWidth = 4, |
| 143 | + Color = SKColor.Parse("#003366"), |
| 144 | + Style = SKPaintStyle.Stroke |
| 145 | +}; |
| 146 | + |
| 147 | +float incrementY = step * MathF.Sqrt(3); |
| 148 | +bool displaceY = false; |
| 149 | +float i = 0; |
| 150 | + |
| 151 | +while (i < width) |
| 152 | +{ |
| 153 | + float y = 0; |
| 154 | + if (!displaceY) |
| 155 | + { |
| 156 | + var (nextX, nextY) = GetNextPoint(i, 0, step); |
| 157 | + y = nextY; |
| 158 | + i = nextX; |
| 159 | + } |
| 160 | + else |
| 161 | + { |
| 162 | + y = 0; |
| 163 | + i += step * 1.5f; |
| 164 | + } |
| 165 | + |
| 166 | + for (float j = y; j < height; j += incrementY) |
| 167 | + { |
| 168 | + var points = GetPoints(i, j, step); |
| 169 | + var path = new SKPath(); |
| 170 | + path.AddPoly(points); |
| 171 | + canvas.DrawPath(path, paint); |
| 172 | + } |
| 173 | + |
| 174 | + displaceY = !displaceY; |
| 175 | +} |
| 176 | + |
| 177 | +bmp.Display(); |
| 178 | +``` |
| 179 | + |
| 180 | +### Explanation |
| 181 | + |
| 182 | +1. **Canvas Setup**: Initializes a canvas with a specified width and height, and clears it with a white background. |
| 183 | +2. **Paint Setup**: Configures the paint with desired properties such as color, stroke width, and style. |
| 184 | +3. **Hexagon Generation**: |
| 185 | + - Calculates the vertical increment (`incrementY`) based on the step size. |
| 186 | + - Uses a `while` loop to iterate horizontally across the canvas. |
| 187 | + - Uses a nested `for` loop to iterate vertically and draw hexagons. |
| 188 | + - Alternates the starting Y-coordinate to create a staggered hexagon grid. |
| 189 | + |
| 190 | +### Result |
| 191 | + |
| 192 | +The above code generates a hexagonal grid pattern as shown in the image below: |
| 193 | + |
| 194 | + |
0 commit comments