Files
beatglow/internal/pixel/image.go
T
2026-10-29 17:29:41 +01:00

109 lines
2.6 KiB
Go

package pixel
import (
"image"
"image/color"
)
// VerticalLSB is a 1 bit (black and white) image.
//
// Each byte is 8 vertical pixels. Each stride is a horizontal band of 8
// pixels high with LSB first. So the first byte represents the following
// pixels, with lowest bit being the top left pixel.
//
// 0 x x x x x x x
// 1 x x x x x x x
// 2 x x x x x x x
// 3 x x x x x x x
// 4 x x x x x x x
// 5 x x x x x x x
// 6 x x x x x x x
// 7 x x x x x x x
//
// It is designed specifically to work with SSD1306 OLED display controller.
type VerticalLSB struct {
// Pix holds the image's pixels, as vertically LSB-first packed bitmap. It
// can be passed directly to ssd1306.Dev.Write()
Pix []byte
// Stride is the Pix stride (in bytes) between vertically adjacent 8 pixels
// horizontal bands.
Stride int
// Rect is the image's bounds.
Rect image.Rectangle
}
// NewVerticalLSB returns an initialized VerticalLSB instance.
func NewVerticalLSB(r image.Rectangle) *VerticalLSB {
w := r.Dx()
// Round down.
minY := r.Min.Y &^ 7
// Round up.
maxY := (r.Max.Y + 7) & ^7
bands := (maxY - minY) / 8
return &VerticalLSB{Pix: make([]byte, w*bands), Stride: w, Rect: r}
}
// ColorModel implements image.Image.
func (i *VerticalLSB) ColorModel() color.Model {
return MonochromeModel
}
// Bounds implements image.Image.
func (i *VerticalLSB) Bounds() image.Rectangle {
return i.Rect
}
// At implements image.Image.
func (i *VerticalLSB) At(x, y int) color.Color {
return i.BitAt(x, y)
}
// BitAt is the optimized version of At().
func (i *VerticalLSB) BitAt(x, y int) Monochrome {
if !(image.Point{x, y}.In(i.Rect)) {
return Off
}
offset, mask := i.PixOffset(x, y)
if i.Pix[offset]&mask != 0 {
return On
}
return Off
}
// Opaque scans the entire image and reports whether it is fully opaque.
func (i *VerticalLSB) Opaque() bool {
return true
}
// PixOffset returns the index of the first element of Pix that corresponds to
// the pixel at (x, y) and the corresponding mask.
func (i *VerticalLSB) PixOffset(x, y int) (int, byte) {
// Adjust band.
minY := i.Rect.Min.Y &^ 7
pY := (y - minY)
offset := pY/8*i.Stride + (x - i.Rect.Min.X)
bit := uint(pY & 7)
return offset, 1 << bit
}
// Set implements draw.Image
func (i *VerticalLSB) Set(x, y int, c color.Color) {
if ToGrayBits(c, 1) == 0 {
i.SetBit(x, y, Off)
}
i.SetBit(x, y, On)
}
// SetBit is the optimized version of Set().
func (i *VerticalLSB) SetBit(x, y int, b Monochrome) {
if !(image.Point{x, y}.In(i.Rect)) {
return
}
offset, mask := i.PixOffset(x, y)
if b == On {
i.Pix[offset] |= mask
} else {
i.Pix[offset] &^= mask
}
}