From e9bce02b24f0dc14560189a811e579240a92f0f7 Mon Sep 17 00:00:00 2001 From: Egon Elbre Date: Wed, 28 Dec 2022 14:13:15 +0200 Subject: [PATCH] unit: add PxToDp and PxToSp PxToDp and PxToSp are useful when you are trying to calculate text-size or widget size based on dynamically sized container. Signed-off-by: Egon Elbre --- unit/unit.go | 10 ++++++++++ unit/unit_test.go | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/unit/unit.go b/unit/unit.go index 58a43903..1cb46d3d 100644 --- a/unit/unit.go +++ b/unit/unit.go @@ -60,6 +60,16 @@ func (c Metric) SpToDp(v Sp) Dp { return Dp(float32(v) * nonZero(c.PxPerSp) / nonZero(c.PxPerDp)) } +// PxToSp converts v px to sp. +func (c Metric) PxToSp(v int) Sp { + return Sp(float32(v) / nonZero(c.PxPerSp)) +} + +// PxToDp converts v px to dp. +func (c Metric) PxToDp(v int) Dp { + return Dp(float32(v) / nonZero(c.PxPerDp)) +} + func nonZero(v float32) float32 { if v == 0. { return 1 diff --git a/unit/unit_test.go b/unit/unit_test.go index 2a9736e9..513ce0e7 100644 --- a/unit/unit_test.go +++ b/unit/unit_test.go @@ -29,4 +29,20 @@ func TestMetric_DpToSp(t *testing.T) { t.Errorf("SpToDp conversion mismatch %v != %v", exp, got) } } + + { + exp := unit.Dp(5) + got := m.PxToDp(m.Dp(5)) + if got != exp { + t.Errorf("PxToDp conversion mismatch %v != %v", exp, got) + } + } + + { + exp := unit.Sp(5) + got := m.PxToSp(m.Sp(5)) + if got != exp { + t.Errorf("PxToSp conversion mismatch %v != %v", exp, got) + } + } }