~mendelmaleh/dummy

ref: 3b6a8213b77745eef0ae7514fcaaf35ffad15892 dummy/image.go -rw-r--r-- 1.5 KiB
3b6a8213Mendel E Rename opt.Pattern -> opt.Mask 1 year, 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main

import (
	"image"
	"image/color"
	"image/draw"

	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"
	"golang.org/x/image/math/fixed"
)

type img struct {
	*image.RGBA
}

func Image(opt Options) image.Image {
	im := img{image.NewRGBA(image.Rectangle{image.Point{}, image.Point{opt.Width, opt.Height}})}

	// image
	switch opt.Mask {
	case "plain":
		draw.Draw(im, im.Bounds(), image.NewUniform(opt.Colors[0]), image.Point{}, draw.Src)
	case "diagonal":
		h, w := float64(im.Bounds().Max.Y-im.Bounds().Min.Y), float64(im.Bounds().Max.X-im.Bounds().Min.X)

		draw.Draw(im, im.Bounds(), image.NewUniform(opt.Colors[0]), image.Point{}, draw.Src)
		draw.DrawMask(im, im.Bounds(), image.NewUniform(opt.Colors[1]), image.Point{}, &diagonal{im, h, w}, image.Point{}, draw.Over)
	}

	// text
	face := truetype.NewFace(opt.Font, &truetype.Options{
		Size:    opt.Size,
		DPI:     opt.DPI,
		Hinting: font.HintingNone,
	})

	// TODO: font color? colors[-1]?
	drawer := &font.Drawer{
		Dst:  im,
		Src:  image.NewUniform(opt.Colors[1]),
		Face: face,
	}

	b, x := font.BoundString(face, opt.Text)
	y := b.Max.Y - b.Min.Y

	drawer.Dot = fixed.Point26_6{
		X: (fixed.I(opt.Width) - x) / 2,
		Y: (fixed.I(opt.Height) + y) / 2,
	}

	drawer.DrawString(opt.Text)

	return im
}

type diagonal struct {
	image.Image
	h, w float64
}

func (im *diagonal) At(x, y int) color.Color {
	if float64(y)+0.5 < im.h-(im.h/im.w)*float64(x) {
		return color.Alpha{}
	}

	return color.Alpha{0xff}
}