github.com/gop9/olt@v0.0.0-20200202132135-d956aad50b08/gio/widget/material/image.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package material
     4  
     5  import (
     6  	"image"
     7  
     8  	"github.com/gop9/olt/gio/f32"
     9  	"github.com/gop9/olt/gio/layout"
    10  	"github.com/gop9/olt/gio/op"
    11  	"github.com/gop9/olt/gio/op/clip"
    12  	"github.com/gop9/olt/gio/op/paint"
    13  	"github.com/gop9/olt/gio/unit"
    14  )
    15  
    16  // Image is a widget that displays an image.
    17  type Image struct {
    18  	// Src is the image to display.
    19  	Src paint.ImageOp
    20  	// Scale is the ratio of image pixels to
    21  	// dps.
    22  	Scale float32
    23  }
    24  
    25  func (t *Theme) Image(img paint.ImageOp) Image {
    26  	return Image{
    27  		Src:   img,
    28  		Scale: 160 / 72, // About 72 DPI.
    29  	}
    30  }
    31  
    32  func (im Image) Layout(gtx *layout.Context) {
    33  	size := im.Src.Size()
    34  	wf, hf := float32(size.X), float32(size.Y)
    35  	w, h := gtx.Px(unit.Dp(wf*im.Scale)), gtx.Px(unit.Dp(hf*im.Scale))
    36  	cs := gtx.Constraints
    37  	d := image.Point{X: cs.Width.Constrain(w), Y: cs.Height.Constrain(h)}
    38  	var s op.StackOp
    39  	s.Push(gtx.Ops)
    40  	clip.Rect{Rect: f32.Rectangle{Max: toPointF(d)}}.Op(gtx.Ops).Add(gtx.Ops)
    41  	im.Src.Add(gtx.Ops)
    42  	paint.PaintOp{Rect: f32.Rectangle{Max: f32.Point{X: float32(w), Y: float32(h)}}}.Add(gtx.Ops)
    43  	s.Pop()
    44  	gtx.Dimensions = layout.Dimensions{Size: d}
    45  }