diff --git a/unit/unit.go b/unit/unit.go index 5e678225..b9ba62ce 100644 --- a/unit/unit.go +++ b/unit/unit.go @@ -44,18 +44,27 @@ type ( // 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))) + return int(math.Round(float64(nonZero(c.PxPerDp)) * 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))) + return int(math.Round(float64(nonZero(c.PxPerSp)) * float64(v))) +} + +// DpToSp converts v dp to sp. +func (c Metric) DpToSp(v Dp) Sp { + return Sp(float32(v) * nonZero(c.PxPerDp) / nonZero(c.PxPerSp)) +} + +// SpToDp converts v sp to dp. +func (c Metric) SpToDp(v Sp) Dp { + return Dp(float32(v) * nonZero(c.PxPerSp) / nonZero(c.PxPerDp)) +} + +func nonZero(v float32) float32 { + if v == 0. { + return 1 + } + return v } diff --git a/unit/unit_test.go b/unit/unit_test.go new file mode 100644 index 00000000..2a9736e9 --- /dev/null +++ b/unit/unit_test.go @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Unlicense OR MIT + +package unit_test + +import ( + "testing" + + "gioui.org/unit" +) + +func TestMetric_DpToSp(t *testing.T) { + m := unit.Metric{ + PxPerDp: 2, + PxPerSp: 3, + } + + { + exp := m.Dp(5) + got := m.Sp(m.DpToSp(5)) + if got != exp { + t.Errorf("DpToSp conversion mismatch %v != %v", exp, got) + } + } + + { + exp := m.Sp(5) + got := m.Dp(m.SpToDp(5)) + if got != exp { + t.Errorf("SpToDp conversion mismatch %v != %v", exp, got) + } + } +}