Is there any easy way to make a centered rect without manually calculating corners?

The title sums it up pretty well. I want to pass a coordinate and a size, and get a rect centered around that coordinate and with that size. This is possible to achieve by calculating the corners a and b as a = center - size/2 and b = center + size/2, or even making a custom wrapper for the #rect() function to do it:

#let aligned-rect(center, size, ..argv) = {
  import cetz.draw: *
  rect(
      (center.at(0) - size.at(0)/2, center.at(1) - size.at(1)/2),
      (center.at(0) + size.at(0)/2, center.at(1) + size.at(1)/2),
      ..argv
    )
}

I was wondering if there was a more idiomatic way of doing it tho.

Yes, you can pass anchor: to move the rect relative to it’s center.
So for centering it, you have to pass anchor: "north-east". Cetz calculates (center - north-east) and offsets the element by that vector.

#import "@preview/cetz:0.5.2" as cetz

#cetz.canvas({
  import cetz.draw: *

  let origin = (1, 2)
  let size = (3, 4)

  grid((-5, -5), (5, 5))

  rect(origin, (rel: size), anchor: "north-east", fill: red.transparentize(50%))
})
})

1 Like