canvas/state.go

55 lines
1.4 KiB
Go

package canvas
import "math"
// Save 保存当前状态
func (c *Context) Save() {
// 深拷贝当前状态
copyState := *c.state
c.states = append(c.states, &copyState)
}
// Restore 恢复上一个状态
func (c *Context) Restore() {
if len(c.states) > 0 {
lastIndex := len(c.states) - 1
c.state = c.states[lastIndex]
c.states = c.states[:lastIndex]
}
}
// Translate 平移变换
func (c *Context) Translate(x, y float64) {
c.state.transform[4] += x*c.state.transform[0] + y*c.state.transform[2]
c.state.transform[5] += x*c.state.transform[1] + y*c.state.transform[3]
}
// Rotate 旋转变换
func (c *Context) Rotate(angle float64) {
sin, cos := math.Sin(angle), math.Cos(angle)
c.Transform(cos, sin, -sin, cos, 0, 0)
}
// Scale 缩放变换
func (c *Context) Scale(sx, sy float64) {
c.Transform(sx, 0, 0, sy, 0, 0)
}
// Transform 应用变换矩阵
func (c *Context) Transform(a, b, cVal, d, e, f float64) {
newMatrix := [6]float64{
a*c.state.transform[0] + cVal*c.state.transform[1],
b*c.state.transform[0] + d*c.state.transform[1],
a*c.state.transform[2] + cVal*c.state.transform[3],
b*c.state.transform[2] + d*c.state.transform[3],
a*c.state.transform[4] + cVal*c.state.transform[5] + e,
b*c.state.transform[4] + d*c.state.transform[5] + f,
}
c.state.transform = newMatrix
}
// SetTransform 设置变换矩阵
func (c *Context) SetTransform(a, b, c1, d, e, f float64) {
c.state.transform = [6]float64{a, b, c1, d, e, f}
}