Skip to content

Commit

Permalink
plotter: add special handling for image.Uniform
Browse files Browse the repository at this point in the history
Fixes #752.

Signed-off-by: Sebastien Binet <[email protected]>
  • Loading branch information
sbinet committed Aug 20, 2022
1 parent b4f15d2 commit 5eb6bf0
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
16 changes: 16 additions & 0 deletions plotter/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ type Image struct {
// (xmin, ymin) and (xmax, ymax) points given in the data space.
// The img will be scaled to fit inside the rectangle.
func NewImage(img image.Image, xmin, ymin, xmax, ymax float64) *Image {
if src, ok := img.(*image.Uniform); ok {
img = uniform{
src,
image.Rect(0, 0, int(xmax-xmin+0.5), int(ymax-ymin+0.5)),
}
}
bounds := img.Bounds()
cols := bounds.Dx()
rows := bounds.Dy()
Expand Down Expand Up @@ -126,3 +132,13 @@ func (img *Image) y(r int) float64 {
}
return img.ymin + float64(r)*img.dy
}

// uniform is a cropped uniform image.
type uniform struct {
*image.Uniform
rect image.Rectangle
}

func (img uniform) Bounds() image.Rectangle {
return img.rect
}
21 changes: 21 additions & 0 deletions plotter/image_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
package plotter_test

import (
"image"
"image/color"
"image/png"
"log"
"os"
Expand Down Expand Up @@ -79,3 +81,22 @@ func ExampleImage_log() {
log.Fatalf("error saving image plot: %v\n", err)
}
}

// An example of embedding a uniform image in a plot.
func ExampleImage_uniform() {
p := plot.New()
p.Title.Text = "Uniform image"

img := image.NewUniform(color.RGBA{R: 90, G: 155, B: 212, A: 255})
p.Add(plotter.NewImage(img, 100, 100, 10000, 10000))

const (
w = 5 * vg.Centimeter
h = 5 * vg.Centimeter
)

err := p.Save(w, h, "testdata/image_plot_uniform.png")
if err != nil {
log.Fatalf("error saving image plot: %v\n", err)
}
}
4 changes: 4 additions & 0 deletions plotter/image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ func TestImagePlot(t *testing.T) {
func TestImagePlot_log(t *testing.T) {
cmpimg.CheckPlot(ExampleImage_log, t, "image_plot_log.png")
}

func TestImagePlot_uniform(t *testing.T) {
cmpimg.CheckPlot(ExampleImage_uniform, t, "image_plot_uniform.png")
}
Binary file added plotter/testdata/image_plot_uniform_golden.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 5eb6bf0

Please sign in to comment.