mirror of
https://git.sr.ht/~eliasnaur/gio
synced 2026-07-06 09:55:40 +00:00
unit: add Metric.DpToSp and Metric.SpToDp
It's sometimes necessary to specify padding or spacing based on the text size. Signed-off-by: Egon Elbre <egonelbre@gmail.com>
This commit is contained in:
+19
-10
@@ -44,18 +44,27 @@ type (
|
|||||||
|
|
||||||
// Dp converts v to pixels, rounded to the nearest integer value.
|
// Dp converts v to pixels, rounded to the nearest integer value.
|
||||||
func (c Metric) Dp(v Dp) int {
|
func (c Metric) Dp(v Dp) int {
|
||||||
s := c.PxPerDp
|
return int(math.Round(float64(nonZero(c.PxPerDp)) * float64(v)))
|
||||||
if s == 0. {
|
|
||||||
s = 1.
|
|
||||||
}
|
|
||||||
return int(math.Round(float64(s) * float64(v)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sp converts v to pixels, rounded to the nearest integer value.
|
// Sp converts v to pixels, rounded to the nearest integer value.
|
||||||
func (c Metric) Sp(v Sp) int {
|
func (c Metric) Sp(v Sp) int {
|
||||||
s := c.PxPerSp
|
return int(math.Round(float64(nonZero(c.PxPerSp)) * float64(v)))
|
||||||
if s == 0. {
|
}
|
||||||
s = 1.
|
|
||||||
}
|
// DpToSp converts v dp to sp.
|
||||||
return int(math.Round(float64(s) * float64(v)))
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user