76 lines
1.6 KiB
Go
76 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"image/color"
|
|
"image/png"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/golang/freetype/truetype"
|
|
"golang.org/x/image/font/gofont/goregular"
|
|
|
|
"git.kingecg.top/kingecg/canvas" // 导入本地canvas包
|
|
)
|
|
|
|
func main() {
|
|
// 创建一个300x200的画布
|
|
ctx := canvas.NewContext(300, 200)
|
|
|
|
// 设置背景色
|
|
ctx.SetFillColor(color.RGBA{240, 240, 240, 255})
|
|
ctx.FillRect(0, 0, 300, 200)
|
|
|
|
// 绘制矩形
|
|
ctx.SetFillColor(color.RGBA{200, 0, 0, 200})
|
|
ctx.FillRect(20, 20, 100, 80)
|
|
|
|
// 绘制圆形
|
|
ctx.BeginPath()
|
|
ctx.SetFillColor(color.RGBA{0, 0, 200, 200})
|
|
ctx.Arc(200, 60, 40, 0, 2*3.14159)
|
|
ctx.Fill()
|
|
|
|
// 创建线性渐变
|
|
gradient := canvas.NewLinearGradient(20, 120, 280, 180)
|
|
gradient.AddColorStop(0, color.RGBA{255, 0, 0, 255})
|
|
gradient.AddColorStop(0.5, color.RGBA{0, 255, 0, 255})
|
|
gradient.AddColorStop(1, color.RGBA{0, 0, 255, 255})
|
|
|
|
// 使用渐变填充矩形
|
|
ctx.SetFillStyle(gradient)
|
|
ctx.FillRect(20, 120, 260, 60)
|
|
|
|
// 绘制文本
|
|
// 加载字体
|
|
font, err := truetype.Parse(goregular.TTF)
|
|
if err != nil {
|
|
log.Fatalf("无法解析字体: %v", err)
|
|
}
|
|
|
|
// 创建字体face
|
|
face := truetype.NewFace(font, &truetype.Options{
|
|
Size: 20,
|
|
})
|
|
|
|
// 设置字体和文本属性
|
|
ctx.SetFont(face)
|
|
ctx.SetTextAlign("center")
|
|
ctx.SetTextBaseline("middle")
|
|
ctx.SetFillColor(color.RGBA{0, 0, 0, 255})
|
|
ctx.FillText("Canvas 示例", 150, 30)
|
|
|
|
// 保存为PNG图片
|
|
img := ctx.Image()
|
|
f, err := os.Create("example.png")
|
|
if err != nil {
|
|
log.Fatalf("无法创建文件: %v", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
if err := png.Encode(f, img); err != nil {
|
|
log.Fatalf("无法编码PNG: %v", err)
|
|
}
|
|
|
|
log.Println("图像已保存为 example.png")
|
|
}
|