在 Golang 中绘制具有两个半径的圆圈

igo*_*ath 1 image draw go

我环顾四周,但找不到任何对在 golang 中绘制圆圈有用的东西。我想绘制一个具有 2 个给定(内部和外部)半径的绘图,并为它们之间的所有像素着色。

一种可能的方法是遍历每个像素并为其着色,直到创建环。虽然,这似乎非常低效。

对此的任何帮助将不胜感激!:)

icz*_*cza 5

请阅读这个相关问题:在 Golang 中绘制一个矩形?

总结一下:标准的 Go 库不提供原始绘图或绘画功能。

所以是的,要么你必须使用第三方库来画一个圆圈(比如github.com/llgcode/draw2d),要么你必须自己做。别担心,这并不难。

画一个圆

首先选择一个简单有效的画圆算法。我推荐中点圆算法

您将在链接的维基百科页面上找到该算法。注意:如果你想使用它,你不必理解它。

但是我们确实需要在 Go 中实现该算法。这很简单:

func drawCircle(img draw.Image, x0, y0, r int, c color.Color) {
    x, y, dx, dy := r-1, 0, 1, 1
    err := dx - (r * 2)

    for x > y {
        img.Set(x0+x, y0+y, c)
        img.Set(x0+y, y0+x, c)
        img.Set(x0-y, y0+x, c)
        img.Set(x0-x, y0+y, c)
        img.Set(x0-x, y0-y, c)
        img.Set(x0-y, y0-x, c)
        img.Set(x0+y, y0-x, c)
        img.Set(x0+x, y0-y, c)

        if err <= 0 {
            y++
            err += dy
            dy += 2
        }
        if err > 0 {
            x--
            dx += 2
            err += dx - (r * 2)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是全部。只需传递一个draw.Image你想画的,和你想画的圆的参数(中心点,半径和颜色)。

让我们看看它的实际效果。让我们创建一个图像,在上面画一个圆圈,然后将图像保存到一个文件中。这就是全部:

img := image.NewRGBA(image.Rect(0, 0, 100, 100))
drawCircle(img, 40, 40, 30, color.RGBA{255, 0, 0, 255})

buf := &bytes.Buffer{}
if err := png.Encode(buf, img); err != nil {
    panic(err)
}
if err := ioutil.WriteFile("circle.png", buf.Bytes(), 0666); err != nil {
    panic(err)
}
Run Code Online (Sandbox Code Playgroud)

注意:您也可以将图像直接编码为 anos.File并“跳过”内存缓冲区。这只是为了演示,并验证我们的实现工作。

画一个圆环(填充两个圆之间的空间)

如果您想自己实现它,这并不是那么简单,但是在这里使用 3rd 方库确实可以派上用场。

虽然它们中的大多数不包含环形绘制支持,但它们确实有圆绘制支持,并且您可以设置用于绘制圆的线的宽度。

因此,将线宽设置为圆的 2 半径之差的值。并以原半径的算术中心为新半径画圆。

这是算法(这不是可运行的代码):

// Helper functions abstracting the library you choose:

func setColor(c color.Color) {}
func setLineWidth(width float64) {}
func drawCircle(r, x, y float64) {}

// fillRing draws a ring, where r1 and r2 are 2 concentric circles,
// the boundaries of the ring, (x, y) being the center point.
func fillRing(r1, r2, x, y float64, c color.color) {
    // Set drawing color:
    setColor(c)

    // Set line width:
    width := r2 - r1
    if width < 0 {
        width = -width
    }
    setLineWidth(width)

    // And finally draw a circle which will be a ring:
    r := (r2 + r1) / 2
    drawCircle(r, x, y)
}
Run Code Online (Sandbox Code Playgroud)