limage - grayalpha.go
1 package limage
2
3 import (
4 "image"
5 "image/color"
6
7 "vimagination.zapto.org/limage/lcolor"
8 )
9
10 // GrayAlpha is an image of GrayAlpha pixels
11 type GrayAlpha struct {
12 Pix []lcolor.GrayAlpha
13 Stride int
14 Rect image.Rectangle
15 }
16
17 // NewGrayAlpha create a new GrayAlpha image with the given bounds
18 func NewGrayAlpha(r image.Rectangle) *GrayAlpha {
19 w, h := r.Dx(), r.Dy()
20 return &GrayAlpha{
21 Pix: make([]lcolor.GrayAlpha, w*h),
22 Stride: w,
23 Rect: r,
24 }
25 }
26
27 // At returns the color for the pixel at the specified coords
28 func (g *GrayAlpha) At(x, y int) color.Color {
29 return g.GrayAlphaAt(x, y)
30 }
31
32 // Bounds returns the limits of the image
33 func (g *GrayAlpha) Bounds() image.Rectangle {
34 return g.Rect
35 }
36
37 // ColorModel returns a color model to transform arbitrary colours into a
38 // GrayAlpha color
39 func (g *GrayAlpha) ColorModel() color.Model {
40 return lcolor.GrayAlphaModel
41 }
42
43 // GrayAlphaAt returns a GrayAlpha colr for the specified coords
44 func (g *GrayAlpha) GrayAlphaAt(x, y int) lcolor.GrayAlpha {
45 if !(image.Point{x, y}.In(g.Rect)) {
46 return lcolor.GrayAlpha{}
47 }
48 return g.Pix[g.PixOffset(x, y)]
49 }
50
51 // Opaque returns true if all pixels have full alpha
52 func (g *GrayAlpha) Opaque() bool {
53 for _, c := range g.Pix {
54 if c.A != 255 {
55 return false
56 }
57 }
58 return true
59 }
60
61 // PixOffset returns the index of the element of Pix corresponding to the given
62 // coords
63 func (g *GrayAlpha) PixOffset(x, y int) int {
64 return (y-g.Rect.Min.Y)*g.Stride + x - g.Rect.Min.X
65 }
66
67 // Set converts the given colour to a GrayAlpha colour and sets it at the given
68 // coords
69 func (g *GrayAlpha) Set(x, y int, c color.Color) {
70 if !(image.Point{x, y}.In(g.Rect)) {
71 return
72 }
73 g.Pix[g.PixOffset(x, y)] = lcolor.GrayAlphaModel.Convert(c).(lcolor.GrayAlpha)
74 }
75
76 // SetGrayAlpha sets the colour at the given coords
77 func (g *GrayAlpha) SetGrayAlpha(x, y int, ga lcolor.GrayAlpha) {
78 if !(image.Point{x, y}.In(g.Rect)) {
79 return
80 }
81 g.Pix[g.PixOffset(x, y)] = ga
82 }
83
84 // SubImage retuns the Image viewable through the given bounds
85 func (g *GrayAlpha) SubImage(r image.Rectangle) image.Image {
86 r = r.Intersect(g.Rect)
87 if r.Empty() {
88 return &GrayAlpha{}
89 }
90 return &GrayAlpha{
91 Pix: g.Pix[g.PixOffset(r.Min.X, r.Min.Y):],
92 Stride: g.Stride,
93 Rect: r,
94 }
95 }
96