~eliasnaur/gio

gio/widget/material/slider.go -rw-r--r-- 2.4 KiB
ef7b3e75Jack Mordaunt widget: delete whole words with key modifier 5 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// SPDX-License-Identifier: Unlicense OR MIT

package material

import (
	"image"
	"image/color"

	"gioui.org/f32"
	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/op/clip"
	"gioui.org/op/paint"
	"gioui.org/unit"
	"gioui.org/widget"
)

// Slider is for selecting a value in a range.
func Slider(th *Theme, float *widget.Float, min, max float32) SliderStyle {
	return SliderStyle{
		Min:   min,
		Max:   max,
		Color: th.Color.Primary,
		Float: float,
	}
}

type SliderStyle struct {
	Min, Max float32
	Color    color.RGBA
	Float    *widget.Float
}

func (s SliderStyle) Layout(gtx layout.Context) layout.Dimensions {
	thumbRadiusInt := gtx.Px(unit.Dp(6))
	trackWidth := float32(gtx.Px(unit.Dp(2)))
	thumbRadius := float32(thumbRadiusInt)
	halfWidthInt := 2 * thumbRadiusInt
	halfWidth := float32(halfWidthInt)

	size := gtx.Constraints.Min
	// Keep a minimum length so that the track is always visible.
	minLength := halfWidthInt + 3*thumbRadiusInt + halfWidthInt
	if size.X < minLength {
		size.X = minLength
	}
	size.Y = 2 * halfWidthInt

	st := op.Push(gtx.Ops)
	op.Offset(f32.Pt(halfWidth, 0)).Add(gtx.Ops)
	gtx.Constraints.Min = image.Pt(size.X-2*halfWidthInt, size.Y)
	s.Float.Layout(gtx, halfWidthInt, s.Min, s.Max)
	thumbPos := halfWidth + s.Float.Pos()
	st.Pop()

	color := s.Color
	if gtx.Queue == nil {
		color = mulAlpha(color, 150)
	}

	// Draw track before thumb.
	st = op.Push(gtx.Ops)
	track := f32.Rectangle{
		Min: f32.Point{
			X: halfWidth,
			Y: halfWidth - trackWidth/2,
		},
		Max: f32.Point{
			X: thumbPos,
			Y: halfWidth + trackWidth/2,
		},
	}
	clip.RRect{Rect: track}.Add(gtx.Ops)
	paint.ColorOp{Color: color}.Add(gtx.Ops)
	paint.PaintOp{Rect: track}.Add(gtx.Ops)
	st.Pop()

	// Draw track after thumb.
	st = op.Push(gtx.Ops)
	track.Min.X = thumbPos
	track.Max.X = float32(size.X) - halfWidth
	clip.RRect{Rect: track}.Add(gtx.Ops)
	paint.ColorOp{Color: mulAlpha(color, 96)}.Add(gtx.Ops)
	paint.PaintOp{Rect: track}.Add(gtx.Ops)
	st.Pop()

	// Draw thumb.
	st = op.Push(gtx.Ops)
	thumb := f32.Rectangle{
		Min: f32.Point{
			X: thumbPos - thumbRadius,
			Y: halfWidth - thumbRadius,
		},
		Max: f32.Point{
			X: thumbPos + thumbRadius,
			Y: halfWidth + thumbRadius,
		},
	}
	rr := thumbRadius
	clip.RRect{
		Rect: thumb,
		NE:   rr, NW: rr, SE: rr, SW: rr,
	}.Add(gtx.Ops)
	paint.ColorOp{Color: color}.Add(gtx.Ops)
	paint.PaintOp{Rect: thumb}.Add(gtx.Ops)
	st.Pop()

	return layout.Dimensions{Size: size}
}