[PATCH gio] unit: add Metric.DpToSp and Metric.SpToDp
Export this patch
From: Egon Elbre <egonelbre@gmail.com>
It's sometimes necessary to specify padding or spacing based on
the text size.
Signed-off-by: Egon Elbre <egonelbre@gmail.com>
---
unit/unit.go | 27 ++++++++++++++++++---------
unit/unit_test.go | 32 ++++++++++++++++++++++++++++++++
2 files changed, 50 insertions(+), 9 deletions(-)
create mode 100644 unit/unit_test.go
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(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 int(math.Round(float64(s) * float64(v)))
+ 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)
+ }
+ }
+}
--
2.34.2
gio/patches: SUCCESS in 20m28s
[unit: add Metric.DpToSp and Metric.SpToDp][0] from [~egonelbre][1]
[0]: https://lists.sr.ht/~eliasnaur/gio-patches/patches/32865
[1]: mailto:egonelbre@gmail.com
✓ #777439 SUCCESS gio/patches/linux.yml https://builds.sr.ht/~eliasnaur/job/777439
✓ #777438 SUCCESS gio/patches/freebsd.yml https://builds.sr.ht/~eliasnaur/job/777438
✓ #777440 SUCCESS gio/patches/openbsd.yml https://builds.sr.ht/~eliasnaur/job/777440
✓ #777437 SUCCESS gio/patches/apple.yml https://builds.sr.ht/~eliasnaur/job/777437
Thanks, merged.
Elias