目录

画线

golang 自带一些图片相关库,但是没有找到画一条直线的函数,网上查找了一番,将结果记录于此。

坐标系

 -----→ x
|
|
↓ y

水平为 x 轴,正方向向右;垂直为 y 轴,正方向向下。

画一条直线

难点为斜线,需要临近的像素点近似为一条直线。

func line(img *image.RGBA, x1, y1, x2, y2 int, c color.Color) {
    delta_x := x2 - x1
    delta_y := y2 - y1
    if delta_x == 0 && delta_y == 0 {
        img.Set(x1, y1, c)
        return
    }

    abs_delta_x := math.Abs(float64(delta_x))
    abs_delta_y := math.Abs(float64(delta_y))

    x := float64(x1)
    y := float64(y1)
    if abs_delta_y > abs_delta_x {
        dx := float64(delta_x) / abs_delta_y
        dy := float64(delta_y) / abs_delta_y
        for i := 0; i <= int(abs_delta_y); i++ {
            img.Set(int(x+0.5), int(y), c)
            x += dx
            y += dy
        }
    } else {
        dx := float64(delta_x) / abs_delta_x
        dy := float64(delta_y) / abs_delta_x
        for i := 0; i <= int(abs_delta_x); i++ {
            img.Set(int(x), int(y+0.5), c)
            x += dx
            y += dy
        }
    }
}

测试

在中心为起始点向 360 度方向发散画线,查看最后图像是否满意。

func Test_line(t *testing.T) {
    img := image.NewRGBA(image.Rect(0, 0, _WIDTH, _HIGH))

    cs := []color.RGBA{
        {255, 0, 0, 255},
        {255, 255, 0, 255},
        {0, 255, 0, 255},
        {0, 255, 255, 255},
        {0, 0, 255, 255},
        {255, 0, 255, 255},
    }
    x0 := _WIDTH / 2
    y0 := _HIGH / 2
    cs_i := 0
    for i := 0; i < _WIDTH; i += 7 {
        x := i
        y := 0
        cs_i++
        line(img, x, y, x0, y0, cs[cs_i%len(cs)])
    }
    for i := 0; i < _HIGH; i += 8 {
        x := _WIDTH
        y := i
        cs_i++
        line(img, x, y, x0, y0, cs[cs_i%len(cs)])
    }
    for i := _WIDTH; i >= 0; i -= 10 {
        x := i
        y := _HIGH
        cs_i++
        line(img, x, y, x0, y0, cs[cs_i%len(cs)])
    }
    for i := _HIGH; i >= 0; i -= 10 {
        x := 0
        y := i
        cs_i++
        line(img, x, y, x0, y0, cs[cs_i%len(cs)])
    }

    // Save to line.png
    f, _ := os.OpenFile("line.png", os.O_WRONLY|os.O_CREATE, 0600)
    defer f.Close()
    png.Encode(f, img)
}