GO 图像操作-遮罩
大约 1 分钟
Go 图像操作-遮罩
GO 1.20 以下两种常用遮罩,用于绘制圆形与圆角矩形
package img
import (
"image"
"image/color"
)
// CircleMask 圆形遮罩
type CircleMask struct {
Radius int
}
func (c CircleMask) ColorModel() color.Model {
return color.AlphaModel
}
func (c CircleMask) Bounds() image.Rectangle {
return image.Rect(0, 0, c.Radius*2, c.Radius*2)
}
func (c CircleMask) At(x, y int) color.Color {
var xx, yy, r = x - c.Radius, y - c.Radius, c.Radius
if xx*xx+yy*yy < r*r {
return color.Alpha{A: 0xFF}
}
return color.Transparent
}
// RoundedRectMask 圆角矩形遮罩
type RoundedRectMask struct {
End image.Point
Radius int
}
func (r RoundedRectMask) ColorModel() color.Model {
return color.AlphaModel
}
func (r RoundedRectMask) Bounds() image.Rectangle {
return image.Rect(0, 0, r.End.X, r.End.Y)
}
func (r RoundedRectMask) At(x, y int) color.Color {
var xx, yy int
rr := r.Radius
inArea := false
if x < rr && y < rr {
xx, yy = x-rr, y-rr
inArea = true
}
if x > r.End.X-rr && y < rr {
xx, yy = x-r.End.X+rr, y-rr
inArea = true
}
if x < rr && y > r.End.Y-rr {
xx, yy = x-rr, y-r.End.Y+rr
inArea = true
}
if x > r.End.X-rr && y > r.End.Y-rr {
xx, yy = x-r.End.X+rr, y-r.End.Y+rr
inArea = true
}
if inArea && xx*xx+yy*yy > rr*rr {
return color.Transparent
}
return color.Alpha{A: 0xFF}
}
使用例
func main() {
dest := image.NewRGBA(image.Rect(0, 0, 500, 500))
//圆形图案
draw.DrawMask(dest, dest.Bounds(), image.NewUniform(color.Black), image.Pt(0, 0),
img.CircleMask{Radius: 250}, image.Pt(0, 0), draw.Over)
//圆角图案
draw.DrawMask(dest, dest.Bounds(), image.NewUniform(color.White), image.Pt(0, 0),
img.RoundedRectMask{End: image.Pt(250, 250), Radius: 30}, image.Pt(-125, -125), draw.Over)
//Output
file, _ := os.Create("dest.png")
_ = png.Encode(file, dest)
}