scale.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package scale
  2. import (
  3. "math"
  4. "fyne.io/fyne/v2"
  5. )
  6. // ToScreenCoordinate converts a fyne coordinate in the given canvas to a screen coordinate
  7. func ToScreenCoordinate(c fyne.Canvas, v float32) int {
  8. return int(math.Ceil(float64(v * c.Scale())))
  9. }
  10. // ToFyneCoordinate converts a screen coordinate for a given canvas to a fyne coordinate
  11. func ToFyneCoordinate(c fyne.Canvas, v int) float32 {
  12. switch c.Scale() {
  13. case 0.0:
  14. panic("Incorrect scale most likely not set.")
  15. case 1.0:
  16. return float32(v)
  17. default:
  18. return float32(v) / c.Scale()
  19. }
  20. }
  21. // ToFyneSize returns the scaled size of an object based on pixel coordinates, typically for images.
  22. // This method will attempt to find the canvas for an object to get its scale.
  23. // In the event that this fails it will assume a 1:1 mapping (scale=1 or low DPI display).
  24. func ToFyneSize(obj fyne.CanvasObject, width, height int) fyne.Size {
  25. app := fyne.CurrentApp()
  26. if app == nil {
  27. return fyne.NewSize(float32(width), float32(height)) // can occur if called before app.New
  28. }
  29. driver := app.Driver()
  30. if driver == nil {
  31. return fyne.NewSize(float32(width), float32(height))
  32. }
  33. c := driver.CanvasForObject(obj)
  34. if c == nil {
  35. return fyne.NewSize(float32(width), float32(height)) // this will happen a lot during init
  36. }
  37. return fyne.NewSize(ToFyneCoordinate(c, width), ToFyneCoordinate(c, height))
  38. }