找出不存储先前添加的圆坐标的重叠圆相当棘手。好消息是,添加圆后,它将覆盖给定半径的区域。如果继续依赖随机性而不使用更有针对性的算法,则必须检查您拥有的圆并确定它们是否重叠,这是通过基本几何公式(例如中心之间的距离)完成的。以下是一个示例,它没有进行大量优化,但应该为您提供一个起点。它不会检查圆的中心+半径是否在画布范围内,它包括将结果绘制到输出文件中的代码。在示例中,我使用了一个小画布,但可以调整为您的矩形大小。该代码应该生成如下图像:
注意:代码并没有以最佳方式编写,有很多可以改进的地方,例如使用指针而不是结构体,或者在绘制时去除循环,或者使用更好的算法来生成每个圆的X、Y和半径,而不是使用随机性。保留HTML标签。
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"math/rand"
"os"
)
const (
width int = 100
height int = 200
)
type Circle struct {
Center image.Point
Radius int
}
func main() {
circles := map[Circle]bool{}
bounds := image.Rectangle{image.Point{0, 0}, image.Point{width, height}}
for i := 0; i < 20; i++ {
c := randomCircle(bounds)
if overlaped(c, circles) {
continue
}
circles[c] = true
}
fmt.Println(circles)
file, err := os.Create("out.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
draw(width, height, circles, file)
file.Close()
}
func overlaped(c Circle, circles map[Circle]bool) bool {
for circle := range circles {
if overlap(circle, c) {
return true
}
}
return false
}
func randomCircle(rect image.Rectangle) Circle {
radius := randomRadius(rect.Max.X, rect.Max.Y) - 1
x := randDim(width-radius, 0)
y := randDim(height-radius, 0)
return Circle{
Center: image.Point{X: x, Y: y},
Radius: radius,
}
}
func randomRadius(width, height int) int {
if width < height {
return rand.Intn(width / 2)
} else {
return rand.Intn(height / 2)
}
}
func randDim(max, min int) int {
return rand.Intn(max) + min
}
func distance(a, b image.Point) int {
return int(math.Sqrt(math.Pow(float64(b.X-a.X), 2) + math.Pow(float64(b.Y-a.Y), 2)))
}
func overlap(a, b Circle) bool {
return distance(a.Center, b.Center) < a.Radius+b.Radius
}
func draw(width, height int, circles map[Circle]bool, file *os.File) error {
img := image.NewRGBA(image.Rect(0, 0, width, height))
for circle := range circles {
for a := 0; a < 360; a++ {
var rads float64 = float64(a) * 0.017453
x := float64(circle.Center.X) + float64(circle.Radius)*math.Cos(rads)
y := float64(circle.Center.Y) + float64(circle.Radius)*math.Sin(rads)
img.Set(int(x), int(y), color.RGBA{R: 255, G: 0, B: 0, A: 255})
}
}
for x := 0; x < width; x++ {
img.Set(int(x), 0, color.RGBA{R: 0, G: 0, B: 255, A: 255})
img.Set(int(x), height-1, color.RGBA{R: 0, G: 0, B: 255, A: 255})
}
for y := 0; y < height; y++ {
img.Set(width-1, y, color.RGBA{R: 0, G: 0, B: 255, A: 255})
img.Set(0, y, color.RGBA{R: 0, G: 0, B: 255, A: 255})
}
return png.Encode(file, img)
}