Gestures
Pan and zoom for custom canvases, from wheels, touchpads and pinches.
Loading the live example…
import (
"github.com/egoist/mygo/ui"
"github.com/oneo-me/onevra/source/components"
"github.com/oneo-me/onevra/source/components/gesture"
)
type zoomCanvas struct {
nav gesture.Navigation
x, y, zoom float32 // the artboard's position and scale
}
func (z *zoomCanvas) View(c *ui.Context) {
t := c.Theme()
canvas := components.PixelGrid(c, components.PixelGridOptions{Spacing: 20}).Fill().Clip()
// Scroll or drag two fingers to pan; use the wheel or pinch to zoom.
z.nav.Handle(c, canvas, func(e gesture.Event) {
switch e.Kind {
case gesture.Pan:
z.x += e.DX
z.y += e.DY
case gesture.Zoom:
next := min(max(z.zoom*float32(e.Scale), 0.25), 4)
// Zoom around the pointer: keep the point under it in place.
f := next / z.zoom
z.x = e.X - (e.X-z.x)*f
z.y = e.Y - (e.Y-z.y)*f
z.zoom = next
}
}, nil)
canvas.Children(func() {
ui.Column(c).Absolute().Left(z.x).Top(z.y).Width(240*z.zoom).Height(160*z.zoom).
Padding(t.Space(4)*z.zoom).Radius(t.Radius*1.5*z.zoom).
Background(t.Surface).Border(1, t.Border).Children(func() {
components.Text(c, "Artboard").Bold().FontSize(t.FontSize * z.zoom)
})
})
}gesture.Navigation turns an element's scrolling into pan and zoom events: a touchpad pans and a pinch zooms, and a mouse wheel zooms. Keep one navigation per element and apply the events to your own camera. Graphs and flow diagrams use it for theirs.
API
Navigation
type Navigation struct {
// contains filtered or unexported fields
}Navigation delivers an element's pan and zoom gestures. Keep one per element; its zero value is ready to use.
Methods
func (n *Navigation) Handle(c *ui.Context, el ui.Element, navigate func(Event), other func(ui.InputEvent) bool) ui.ElementHandle has el take its input through fn, as HandleInput does, after sending scrolling and pinches to navigate. Navigation events reach navigate and are taken; other input goes to other, which may be nil. Call it on each build.
Event
Kind
type Kind uint8Kind is the kind of a navigation Event.
const (
// Pan moves the content by DX, DY DIPs: positive DX moves it right.
Pan Kind = iota + 1
// Zoom scales the content by Scale around X, Y.
Zoom
)Classify
func Classify(ev ui.InputEvent) (Event, bool)Classify maps a scroll or pinch to navigation. A pinch zooms; a touchpad pans unless Control or Command is held, which zooms as a pinch does; a wheel zooms, except a sideways wheel, or Shift with a vertical one on macOS, which pans across. Call it while handling the event; ok is false for other input.
pkg.go.devDeviceOf
func DeviceOf(ev ui.InputEvent) DeviceDeviceOf reports which device produced an InputScroll. Call it while handling the event, before returning from HandleInput.
pkg.go.dev