image.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. package widget
  3. import (
  4. "image"
  5. "gioui.org/f32"
  6. "gioui.org/layout"
  7. "gioui.org/op"
  8. "gioui.org/op/clip"
  9. "gioui.org/op/paint"
  10. "gioui.org/unit"
  11. )
  12. // Image is a widget that displays an image.
  13. type Image struct {
  14. // Src is the image to display.
  15. Src paint.ImageOp
  16. // Fit specifies how to scale the image to the constraints.
  17. // By default it does not do any scaling.
  18. Fit Fit
  19. // Position specifies where to position the image within
  20. // the constraints.
  21. Position layout.Direction
  22. // Scale is the factor used for converting image pixels to dp.
  23. // If Scale is zero it defaults to 1.
  24. //
  25. // To map one image pixel to one output pixel, set Scale to 1.0 / gtx.Metric.PxPerDp.
  26. Scale float32
  27. }
  28. func (im Image) Layout(gtx layout.Context) layout.Dimensions {
  29. scale := im.Scale
  30. if scale == 0 {
  31. scale = 1
  32. }
  33. size := im.Src.Size()
  34. wf, hf := float32(size.X), float32(size.Y)
  35. w, h := gtx.Dp(unit.Dp(wf*scale)), gtx.Dp(unit.Dp(hf*scale))
  36. dims, trans := im.Fit.scale(gtx.Constraints, im.Position, layout.Dimensions{Size: image.Pt(w, h)})
  37. defer clip.Rect{Max: dims.Size}.Push(gtx.Ops).Pop()
  38. pixelScale := scale * gtx.Metric.PxPerDp
  39. trans = trans.Mul(f32.Affine2D{}.Scale(f32.Point{}, f32.Pt(pixelScale, pixelScale)))
  40. defer op.Affine(trans).Push(gtx.Ops).Pop()
  41. im.Src.Add(gtx.Ops)
  42. paint.PaintOp{}.Add(gtx.Ops)
  43. return dims
  44. }