unit.mx raw

   1  // SPDX-License-Identifier: Unlicense OR MIT
   2  
   3  // Device independent units: dp, sp, and px conversions.
   4  // Ported from gioui.org/unit.
   5  
   6  package gio
   7  
   8  import (
   9  	"math"
  10  )
  11  
  12  // Metric converts Dp and Sp values to device-dependent pixels.
  13  // The zero value represents a 1-to-1 scale from dp, sp to pixels.
  14  type Metric struct {
  15  	// PxPerDp is the device-dependent pixels per dp.
  16  	PxPerDp float32
  17  	// PxPerSp is the device-dependent pixels per sp.
  18  	PxPerSp float32
  19  }
  20  
  21  type (
  22  	// Dp represents device independent pixels. 1 dp will
  23  	// have the same apparent size across platforms and
  24  	// display resolutions.
  25  	Dp float32
  26  	// Sp is like Dp but for font sizes.
  27  	Sp float32
  28  )
  29  
  30  // Dp converts v to pixels, rounded to the nearest integer value.
  31  func (c Metric) Dp(v Dp) int {
  32  	return int(math.Round(float64(nonZero(c.PxPerDp)) * float64(v)))
  33  }
  34  
  35  // Sp converts v to pixels, rounded to the nearest integer value.
  36  func (c Metric) Sp(v Sp) int {
  37  	return int(math.Round(float64(nonZero(c.PxPerSp)) * float64(v)))
  38  }
  39  
  40  // DpToSp converts v dp to sp.
  41  func (c Metric) DpToSp(v Dp) Sp {
  42  	return Sp(float32(v) * nonZero(c.PxPerDp) / nonZero(c.PxPerSp))
  43  }
  44  
  45  // SpToDp converts v sp to dp.
  46  func (c Metric) SpToDp(v Sp) Dp {
  47  	return Dp(float32(v) * nonZero(c.PxPerSp) / nonZero(c.PxPerDp))
  48  }
  49  
  50  // PxToSp converts v px to sp.
  51  func (c Metric) PxToSp(v int) Sp {
  52  	return Sp(float32(v) / nonZero(c.PxPerSp))
  53  }
  54  
  55  // PxToDp converts v px to dp.
  56  func (c Metric) PxToDp(v int) Dp {
  57  	return Dp(float32(v) / nonZero(c.PxPerDp))
  58  }
  59  
  60  func nonZero(v float32) float32 {
  61  	if v == 0. {
  62  		return 1
  63  	}
  64  	return v
  65  }
  66