From c91cea12a15b34fd39933738df7291fa92b824b3 Mon Sep 17 00:00:00 2001 From: Kaustubh Maske Patil <37668193+nikochiko@users.noreply.github.com> Date: Fri, 26 Jan 2024 20:10:44 +0530 Subject: [PATCH] Fix #92: centering for rectangle shape (#93) --- examples/dune | 5 +++++ examples/rectangle.ml | 7 ++----- examples/square.ml | 10 ++++++++++ lib/shape.ml | 13 +++++++------ 4 files changed, 24 insertions(+), 11 deletions(-) create mode 100644 examples/square.ml diff --git a/examples/dune b/examples/dune index ca6ebee..1c42610 100644 --- a/examples/dune +++ b/examples/dune @@ -83,6 +83,11 @@ (modules rectangle_canvas) (libraries joy)) +(executable + (name square) + (modules square) + (libraries joy)) + (executable (name star) (modules star) diff --git a/examples/rectangle.ml b/examples/rectangle.ml index 32707ba..282a2b4 100644 --- a/examples/rectangle.ml +++ b/examples/rectangle.ml @@ -1,12 +1,9 @@ open Joy -let size = 100 - let () = init (); background (255, 255, 255, 255); - (* creating a rectangle from points *) - let rect = rectangle size size in set_color (0, 0, 0); - render rect; + let r = rectangle 100 200 in + show [r]; write ~filename:"rectangle.png" () diff --git a/examples/square.ml b/examples/square.ml new file mode 100644 index 0000000..d367be0 --- /dev/null +++ b/examples/square.ml @@ -0,0 +1,10 @@ +open Joy + +let () = + init (); + background (255, 255, 255, 255); + let square = rectangle 100 100 in + set_color (0, 0, 0); + show [square]; + write ~filename:"square.png" () + diff --git a/lib/shape.ml b/lib/shape.ml index 348b9b9..b47b594 100644 --- a/lib/shape.ml +++ b/lib/shape.ml @@ -30,14 +30,15 @@ let center = { x = 0.; y = 0. } let circle ?(c = center) r = Circle { c; radius = float_of_int r } let rectangle ?(c = center) width height = - let width, height = (float_of_int width, float_of_int height) in - let { x; y } = c -! ((width +. height) /. 4.) in + let w, h = (float_of_int width, float_of_int height) in + let x1 = c.x -. (w /. 2.) in + let y1 = c.x -. (h /. 2.) in Polygon [ - { x; y }; - { x; y = y +. height }; - { x = x +. width; y = y +. height }; - { x = x +. width; y }; + { x = x1; y = y1 }; + { x = x1; y = y1 +. h }; + { x = x1 +. w; y = y1 +. h }; + { x = x1 +. w; y = y1 }; ] let ellipse ?(c = center) rx ry =