monorepo/hex-grid/src/utilities.rs

47 lines
1.4 KiB
Rust

use cairo::{Context, Path};
pub fn hexagon_path(
context: &Context,
translate_x: f64,
translate_y: f64,
width: f64,
height: f64,
) -> Path {
context.new_path();
let points = hexagon(width, height);
context.move_to(translate_x + points[0].0, translate_y + points[0].1);
context.line_to(translate_x + points[1].0, translate_y + points[1].1);
context.line_to(translate_x + points[2].0, translate_y + points[2].1);
context.line_to(translate_x + points[3].0, translate_y + points[3].1);
context.line_to(translate_x + points[4].0, translate_y + points[4].1);
context.line_to(translate_x + points[5].0, translate_y + points[5].1);
context.copy_path().expect("to successfully copy a path")
}
pub fn hexagon(width: f64, height: f64) -> Vec<(f64, f64)> {
let center_x = width / 2.;
let center_y = height / 2.;
let radius = width / 2.;
vec![
(center_x + radius, center_y),
(
center_x + radius / 2.,
center_y + (3_f64).sqrt() * radius / 2.,
),
(
center_x - radius / 2.,
center_y + (3_f64).sqrt() * radius / 2.,
),
(center_x - radius, center_y),
(
center_x - radius / 2.,
center_y - (3_f64).sqrt() * radius / 2.,
),
(
center_x + radius / 2.,
center_y - (3_f64).sqrt() * radius / 2.,
),
]
}