image.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gui
  5. import (
  6. "github.com/g3n/engine/texture"
  7. "image"
  8. )
  9. // Image is a Panel which contains a single Image
  10. type Image struct {
  11. Panel // Embedded panel
  12. tex *texture.Texture2D // pointer to image texture
  13. }
  14. // NewImage creates and returns an image panel with the image
  15. // from the specified image used as a texture.
  16. // Initially the size of the panel content area is the exact size of the image.
  17. func NewImage(imgfile string) (image *Image, err error) {
  18. tex, err := texture.NewTexture2DFromImage(imgfile)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return NewImageFromTex(tex), nil
  23. }
  24. // NewImageFromRGBA creates and returns an image panel from the
  25. // specified image
  26. func NewImageFromRGBA(rgba *image.RGBA) *Image {
  27. tex := texture.NewTexture2DFromRGBA(rgba)
  28. return NewImageFromTex(tex)
  29. }
  30. // NewImageFromTex creates and returns an image panel from the specified texture2D
  31. func NewImageFromTex(tex *texture.Texture2D) *Image {
  32. i := new(Image)
  33. i.Panel.Initialize(i, 0, 0)
  34. i.tex = tex
  35. i.Panel.SetContentSize(float32(i.tex.Width()), float32(i.tex.Height()))
  36. i.Material().AddTexture(i.tex)
  37. return i
  38. }
  39. // SetTexture changes the image texture to the specified texture2D.
  40. // It returns a pointer to the previous texture.
  41. func (i *Image) SetTexture(tex *texture.Texture2D) *texture.Texture2D {
  42. prevtex := i.tex
  43. i.Material().RemoveTexture(prevtex)
  44. i.tex = tex
  45. i.Panel.SetContentSize(float32(i.tex.Width()), float32(i.tex.Height()))
  46. i.Material().AddTexture(i.tex)
  47. return prevtex
  48. }
  49. // SetImage sets the image from the specified image file
  50. func (i *Image) SetImage(imgfile string) error {
  51. tex, err := texture.NewTexture2DFromImage(imgfile)
  52. if err != nil {
  53. return err
  54. }
  55. i.SetTexture(tex)
  56. return nil
  57. }