gioui.org/ui@v0.0.0-20190926171558-ce74bc0cbaea/paint/paint.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package paint
     4  
     5  import (
     6  	"encoding/binary"
     7  	"image"
     8  	"image/color"
     9  	"math"
    10  
    11  	"gioui.org/ui"
    12  	"gioui.org/ui/f32"
    13  	"gioui.org/ui/internal/opconst"
    14  )
    15  
    16  // ImageOp sets the material to a section of an
    17  // image.
    18  type ImageOp struct {
    19  	// Src is the image.
    20  	Src image.Image
    21  	// Rect defines the section of Src to use.
    22  	Rect image.Rectangle
    23  }
    24  
    25  // ColorOp sets the material to a constant color.
    26  type ColorOp struct {
    27  	Color color.RGBA
    28  }
    29  
    30  // PaintOp draws the current material, respecting the
    31  // clip path and transformation.
    32  type PaintOp struct {
    33  	Rect f32.Rectangle
    34  }
    35  
    36  func (i ImageOp) Add(o *ui.Ops) {
    37  	data := make([]byte, opconst.TypeImageLen)
    38  	data[0] = byte(opconst.TypeImage)
    39  	bo := binary.LittleEndian
    40  	bo.PutUint32(data[1:], uint32(i.Rect.Min.X))
    41  	bo.PutUint32(data[5:], uint32(i.Rect.Min.Y))
    42  	bo.PutUint32(data[9:], uint32(i.Rect.Max.X))
    43  	bo.PutUint32(data[13:], uint32(i.Rect.Max.Y))
    44  	o.Write(data, i.Src)
    45  }
    46  
    47  func (c ColorOp) Add(o *ui.Ops) {
    48  	data := make([]byte, opconst.TypeColorLen)
    49  	data[0] = byte(opconst.TypeColor)
    50  	data[1] = c.Color.R
    51  	data[2] = c.Color.G
    52  	data[3] = c.Color.B
    53  	data[4] = c.Color.A
    54  	o.Write(data)
    55  }
    56  
    57  func (d PaintOp) Add(o *ui.Ops) {
    58  	data := make([]byte, opconst.TypePaintLen)
    59  	data[0] = byte(opconst.TypePaint)
    60  	bo := binary.LittleEndian
    61  	bo.PutUint32(data[1:], math.Float32bits(d.Rect.Min.X))
    62  	bo.PutUint32(data[5:], math.Float32bits(d.Rect.Min.Y))
    63  	bo.PutUint32(data[9:], math.Float32bits(d.Rect.Max.X))
    64  	bo.PutUint32(data[13:], math.Float32bits(d.Rect.Max.Y))
    65  	o.Write(data)
    66  }
    67  
    68  // RectClip returns a ClipOp corresponding to a pixel aligned
    69  // rectangular area.
    70  func RectClip(r image.Rectangle) ClipOp {
    71  	return ClipOp{bounds: toRectF(r)}
    72  }
    73  
    74  func toRectF(r image.Rectangle) f32.Rectangle {
    75  	return f32.Rectangle{
    76  		Min: f32.Point{X: float32(r.Min.X), Y: float32(r.Min.Y)},
    77  		Max: f32.Point{X: float32(r.Max.X), Y: float32(r.Max.Y)},
    78  	}
    79  }