Files
gio-patched/unit/unit.go
T
Elias Naur 3d37491342 all: [API] replace unit.Value with separate unit.Dp, unit.Sp types
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>
2022-05-31 10:24:09 +02:00

62 lines
1.4 KiB
Go

// SPDX-License-Identifier: Unlicense OR MIT
/*
Package unit implements device independent units.
Device independent pixel, or dp, is the unit for sizes independent of
the underlying display device.
Scaled pixels, or sp, is the unit for text sizes. An sp is like dp with
text scaling applied.
Finally, pixels, or px, is the unit for display dependent pixels. Their
size vary between platforms and displays.
To maintain a constant visual size across platforms and displays, always
use dps or sps to define user interfaces. Only use pixels for derived
values.
*/
package unit
import (
"math"
)
// Metric converts Values to device-dependent pixels, px. The zero
// value represents a 1-to-1 scale from dp, sp to pixels.
type Metric struct {
// PxPerDp is the device-dependent pixels per dp.
PxPerDp float32
// PxPerSp is the device-dependent pixels per sp.
PxPerSp float32
}
type (
// Dp represents device independent pixels. 1 dp will
// have the same apparent size across platforms and
// display resolutions.
Dp float32
// Sp is like UnitDp but for font sizes.
Sp float32
)
// Dp converts v to pixels, rounded to the nearest integer value.
func (c Metric) Dp(v Dp) int {
s := c.PxPerDp
if s == 0. {
s = 1.
}
return int(math.Round(float64(s) * float64(v)))
}
// Sp converts v to pixels, rounded to the nearest integer value.
func (c Metric) Sp(v Sp) int {
s := c.PxPerSp
if s == 0. {
s = 1.
}
return int(math.Round(float64(s) * float64(v)))
}