Skip to content

Instantly share code, notes, and snippets.

@sairus7
Last active May 19, 2020 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sairus7/66a1d00fbe8f35319fa62ca3fafd1c65 to your computer and use it in GitHub Desktop.
Save sairus7/66a1d00fbe8f35319fa62ca3fafd1c65 to your computer and use it in GitHub Desktop.
Drag and reshape rectangle with MakieLayout.jl
using Makie
using MakieLayout
## drag + reshape rectangle
scene, layout = layoutscene()
ax = layout[1, 1] = LAxis(scene)
lines!(ax, [0,250,500], [0,500,0])
tightlimits!(ax)
start_pos = Ref(Point2f0(0, 0))
prev_pos = Ref(Point2f0(0, 0))
current_pos = Ref(Point2f0(0, 0))
mode_xreshape = Ref((false,false)) # left, right
mode_yreshape = Ref((false,false)) # bottom, top
rectnode = Node(BBox(10, 100, 10, 100))
rectplot = Ref{Union{Nothing, Poly}}(poly!(ax, rectnode, color = (:blue, 0.05), strokecolor = (:blue, 0.5),
strokewidth = 2,xautolimits = false, yautolimits = false, visible = true))
function rect2coord(r)
x1 = r.origin[1]
x2 = r.origin[1] + r.widths[1]
y1 = r.origin[2]
y2 = r.origin[2] + r.widths[2]
return x1, x2, y1, y2
end
scenestate = MakieLayout.addmousestate!(ax.scene)
MakieLayout.onmouseleftdragstart(scenestate) do state
prev_pos[] = state.pos # start_pos[] = state.pos
x1, x2, y1, y2 = rect2coord(rectnode[])
xbnd = (x2 - x1) / 8 # rect bound x-width
ybnd = (y2 - y1) / 8 # rect bound y-width
mode_xreshape[] = (state.pos[1] < x1 + xbnd, x2 - xbnd < state.pos[1])
mode_yreshape[] = (state.pos[2] < y1 + xbnd, y2 - xbnd < state.pos[2])
end
MakieLayout.onmouseleftdrag(scenestate) do state
current_pos[] = state.pos
c = current_pos[]
p = prev_pos[]
delta = c - p
x_ = mode_xreshape[]
y_ = mode_yreshape[]
if !(x_[1] || x_[2] || y_[1] || y_[2]) # move mode
rectnode[] = rectnode[] + delta
else # reshape mode
x1, x2, y1, y2 = rect2coord(rectnode[])
if x_[1]
x1 += delta[1]
if x2 < x1 # flip bounds
mode_xreshape[] = (false, true)
x1, x2 = x2, x1
end
elseif x_[2]
x2 += delta[1]
if x2 < x1 # flip bounds
mode_xreshape[] = (true, false)
x1, x2 = x2, x1
end
end
if y_[1]
y1 += delta[2]
if y2 < y1 # flip bounds
mode_yreshape[] = (false, true)
y1, y2 = y2, y1
end
elseif y_[2]
y2 += delta[2]
if y2 < y1 # flip bounds
mode_yreshape[] = (true, false)
y1, y2 = y2, y1
end
end
rectnode[] = let
BBox(x1, x2, y1, y2)
end
end
prev_pos[] = c
end
scene
record(scene, "drag_reshape.mp4", 1:255*1.5, framerate=60) do i
sleep(1/60)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment