mirror of
https://git.sr.ht/~eliasnaur/gio
synced 2026-07-01 23:55:39 +00:00
3d37491342
The unit.Value is a struct and thus more inconvenient to use than its
underlying float32 type. In addition, most uses don't need a general
value, but rather a specific unit given by the context. This change
replaces unit.Value with two float32 units, Dp and Sp. It also changes
variables and parameters of unit.Value to a specific unit type matching
the context. That is, unit.Dp everywhere except for text sizes which are
in Sp.
Switching to typed float32s has multiple advantages
- They can be constants:
const touchSlop = unit.Dp(16)
- Casting untyped constants is no longer necessary:
insets := layout.UniformInset(16)
- Calculation with values is natural:
func (s ScrollbarStyle) Width() unit.Dp {
return s.Indicator.MinorWidth + s.Track.MinorPadding + s.Track.MinorPadding
}
The main API change is that calls to gtx.Px must be replaced with either
gtx.Dp or gtx.Sp depending on the unit.
Idea by Christophe Meessen.
Signed-off-by: Elias Naur <mail@eliasnaur.com>
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
// SPDX-License-Identifier: Unlicense OR MIT
|
|
|
|
package material
|
|
|
|
import (
|
|
"image"
|
|
"image/color"
|
|
|
|
"gioui.org/internal/f32color"
|
|
"gioui.org/layout"
|
|
"gioui.org/op/clip"
|
|
"gioui.org/op/paint"
|
|
"gioui.org/unit"
|
|
)
|
|
|
|
type ProgressBarStyle struct {
|
|
Color color.NRGBA
|
|
TrackColor color.NRGBA
|
|
Progress float32
|
|
}
|
|
|
|
func ProgressBar(th *Theme, progress float32) ProgressBarStyle {
|
|
return ProgressBarStyle{
|
|
Progress: progress,
|
|
Color: th.Palette.ContrastBg,
|
|
TrackColor: f32color.MulAlpha(th.Palette.Fg, 0x88),
|
|
}
|
|
}
|
|
|
|
func (p ProgressBarStyle) Layout(gtx layout.Context) layout.Dimensions {
|
|
shader := func(width int, color color.NRGBA) layout.Dimensions {
|
|
const maxHeight = unit.Dp(4)
|
|
rr := gtx.Dp(2)
|
|
|
|
d := image.Point{X: width, Y: gtx.Dp(maxHeight)}
|
|
|
|
defer clip.UniformRRect(image.Rectangle{Max: image.Pt(width, d.Y)}, rr).Push(gtx.Ops).Pop()
|
|
paint.ColorOp{Color: color}.Add(gtx.Ops)
|
|
paint.PaintOp{}.Add(gtx.Ops)
|
|
|
|
return layout.Dimensions{Size: d}
|
|
}
|
|
|
|
progressBarWidth := gtx.Constraints.Max.X
|
|
return layout.Stack{Alignment: layout.W}.Layout(gtx,
|
|
layout.Stacked(func(gtx layout.Context) layout.Dimensions {
|
|
return shader(progressBarWidth, p.TrackColor)
|
|
}),
|
|
layout.Stacked(func(gtx layout.Context) layout.Dimensions {
|
|
fillWidth := int(float32(progressBarWidth) * clamp1(p.Progress))
|
|
fillColor := p.Color
|
|
if gtx.Queue == nil {
|
|
fillColor = f32color.Disabled(fillColor)
|
|
}
|
|
return shader(fillWidth, fillColor)
|
|
}),
|
|
)
|
|
}
|
|
|
|
// clamp1 limits v to range [0..1].
|
|
func clamp1(v float32) float32 {
|
|
if v >= 1 {
|
|
return 1
|
|
} else if v <= 0 {
|
|
return 0
|
|
} else {
|
|
return v
|
|
}
|
|
}
|