Concept
- A hexagon consists of six vertices.
- Given one vertex coordinate, we can find all other vertices as the angle between two edges is 120 degrees.
- Consider a starting point (x, y) and the width of an edge b.
- The right neighbor points will be (x + b, y).
- The right neighbor of the right neighbor will be (x + b + b * Cos(60), y + b * Sin(60)) and so on.
Example
Code Implementation
SkiaSharp Setup
- Refer to the SkiaSharp setup guide
Importing Skiasharp Library
|
|
Importing name space
|
|
Function to Get Hexagon Points from a Single Coordinate
|
|
Function to Get Next Starting Point
|
|
- This function calculates the next starting coordinate from (x, y).
- So we will have two starting point
- both will come alternatively
- Below Code Generate the possible points
|
|
final Code
I am Drawing hexagonal Shape in vertically fashion
Line number 22 that is while loop is for width of image Horizontaly
Line number 37 for vertically for height
Line Number 25 to 36 will deside next verticall starting cordinate points.
|
|
Explanation
- Canvas Setup: Initializes a canvas with a specified width and height, and clears it with a white background.
- Paint Setup: Configures the paint with desired properties such as color, stroke width, and style.
- Hexagon Generation:
- Calculates the vertical increment (
incrementY
) based on the step size. - Uses a
while
loop to iterate horizontally across the canvas. - Uses a nested
for
loop to iterate vertically and draw hexagons. - Alternates the starting Y-coordinate to create a staggered hexagon grid.
- Calculates the vertical increment (
Result
The above code generates a hexagonal grid pattern as shown in the image below: