Created
February 25, 2024 03:43
-
-
Save yutannihilation/2b47f441ff63577d0966da21125f1fb6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(grid) | |
rect <- function(size, rot_deg) { | |
theta <- (c(1 / 4, 3 / 4, 5 / 4, 7 / 4) - rot_deg / 360) * pi | |
rectGrob(x = size * sqrt(2) * sin(theta), | |
y = size * sqrt(2) * cos(theta)) | |
} | |
size <- unit(100, "points") | |
x_orig <- unit(0.5, "npc") | |
y_orig <- unit(0.5, "npc") | |
gp1 <- gpar(col = "darkgreen", lwd = 2.7) | |
gp2 <- gpar(col = "blue", | |
fill = "blue", | |
alpha = 0.2) | |
draw <- function(angle) { | |
angle <- angle %% 180 | |
# flip when angle is larger than 45 | |
if (angle <= 45) { | |
d <- size / cos(pi * angle / 180) # distance between two rectangles | |
size1 <- size # size of main rectangles | |
size2 <- size * tan(pi * angle / 180) # size of complement rectangles | |
} else { | |
d <- size / cos(pi * (90 - angle) / 180) | |
size1 <- size / tan(pi * angle / 180) | |
size2 <- size | |
} | |
d1 <- d # distance between main rectangles | |
d2 <- d / 2 # distance between complement rectangles | |
grid.newpage() | |
# draw main rectangles | |
idx <- expand.grid(x = -2:2, y = -2:2) | |
for (i in seq_len(nrow(idx))) { | |
vp <- viewport( | |
x = x_orig + d1 * idx[i, "x"], | |
y = y_orig + d1 * idx[i, "y"], | |
width = size1, | |
height = size1, | |
angle = angle | |
) | |
grid.draw(rectGrob(gp = gp1, vp = vp)) | |
} | |
# draw complement rectangles | |
idx2 <- expand.grid(x = c(-5L, -3L, -1L, 1L, 3L, 5L), y = c(-5L, -3L, -1L, 1L, 3L, 5L)) | |
for (i in seq_len(nrow(idx2))) { | |
vp <- viewport( | |
x = x_orig + d2 * idx2[i, "x"], | |
y = y_orig + d2 * idx2[i, "y"], | |
width = size2, | |
height = size2, | |
angle = angle | |
) | |
grid.draw(rectGrob(gp = gp2, vp = vp)) | |
} | |
} | |
d <- tempfile() | |
dir.create(d) | |
ragg::agg_png(file.path(d, "plot%03d.png")) | |
for (i in 0:180) { | |
draw(i * 1.0) | |
} | |
dev.off() | |
gifski::gifski(list.files(d, full.names = TRUE), delay = 0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment