gpt4 book ai didi

image - 在 Golang 中绘制两个半径的圆

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:04 26 4
gpt4 key购买 nike

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

一种可能的方法是遍历每个像素并为其着色,直到创建环为止。虽然,这看起来效率很低。

如有任何帮助,我们将不胜感激! :)

最佳答案

请阅读此相关问题:Draw a rectangle in Golang?

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

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

画一个圆

首先选择一个简单高效的画圆算法。我推荐Midpoint circle algorithm .

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

但是我们确实需要在 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)
}
}
}

这就是全部。只需传递一个 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)
}

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

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

如果您想自己实现它,这不是那么简单,但是在这里使用第 3 方库真的会派上用场。

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

因此,将线宽设置为圆的 2 个半径的差值。并以原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)
}

关于image - 在 Golang 中绘制两个半径的圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com