| 1 | // Copyright 2016 The Go 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 | |
| 5 | package widget |
| 6 | |
| 7 | import ( |
| 8 | "image" |
| 9 | "image/draw" |
| 10 | |
| 11 | "golang.org/x/exp/shiny/widget/node" |
| 12 | "golang.org/x/exp/shiny/widget/theme" |
| 13 | ) |
| 14 | |
| 15 | // TODO: mask and maskPoint, not just src and srcRect. |
| 16 | |
| 17 | // TODO: be able to specify the draw operator: Src instead of Over. |
| 18 | |
| 19 | // TODO: if the measured size differs from the actual size, specify a |
| 20 | // background color (or tile-able image like a checkerboard)? Specify a |
| 21 | // draw.Scaler from the golang.org/x/image/draw package? Be able to center the |
| 22 | // source image within the widget? |
| 23 | |
| 24 | // Image is a leaf widget that paints an image.Image. |
| 25 | type Image struct { |
| 26 | node.LeafEmbed |
| 27 | Src image.Image |
| 28 | SrcRect image.Rectangle |
| 29 | } |
| 30 | |
| 31 | // NewImage returns a new Image widget for the part of a source image defined |
| 32 | // by src and srcRect. |
| 33 | func NewImage(src image.Image, srcRect image.Rectangle) *Image { |
| 34 | w := &Image{ |
| 35 | Src: src, |
| 36 | SrcRect: srcRect, |
| 37 | } |
| 38 | w.Wrapper = w |
| 39 | return w |
| 40 | } |
| 41 | |
| 42 | func (w *Image) Measure(t *theme.Theme, widthHint, heightHint int) { |
| 43 | w.MeasuredSize = w.SrcRect.Size() |
| 44 | } |
| 45 | |
| 46 | func (w *Image) PaintBase(ctx *node.PaintBaseContext, origin image.Point) error { |
| 47 | w.Marks.UnmarkNeedsPaintBase() |
| 48 | if w.Src == nil { |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | // wRect is the widget's layout rectangle, in dst's coordinate space. |
| 53 | wRect := w.Rect.Add(origin) |
| 54 | |
| 55 | // sRect is the source image rectangle, in dst's coordinate space, so that |
| 56 | // the upper-left corner of the source image rectangle aligns with the |
| 57 | // upper-left corner of wRect. |
| 58 | sRect := w.SrcRect.Add(wRect.Min.Sub(w.SrcRect.Min)) |
| 59 | |
| 60 | draw.Draw(ctx.Dst, wRect.Intersect(sRect), w.Src, w.SrcRect.Min, draw.Over) |
| 61 | return nil |
| 62 | } |