To create a new image and draw basic shapes in Go, you can make use of the image
and draw
packages from the golang.org/x/image
library. Here's an example code snippet that demonstrates this:
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
// Create a new RGBA image with a white background
img := image.NewRGBA(image.Rect(0, 0, 200, 200))
draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.ZP, draw.Src)
// Create a red rectangle at coordinates (50, 50) to (150, 150)
rect := image.Rect(50, 50, 150, 150)
draw.Draw(img, rect, image.NewUniform(color.RGBA{255, 0, 0, 255}), image.ZP, draw.Src)
// Create a blue circle at center (100, 100) with radius 40
circleCenter := image.Point{100, 100}
circleRadius := 40
drawCircle(img, circleCenter, circleRadius, color.RGBA{0, 0, 255, 255})
// Save the image to a file
file, err := os.Create("output.png")
if err != nil {
panic(err)
}
defer file.Close()
png.Encode(file, img)
}
// Helper function to draw a circle on an image
func drawCircle(img draw.Image, center image.Point, radius int, color color.Color) {
x := radius
y := 0
radiusError := 1 - x
for x >= y {
img.Set(center.X+x, center.Y+y, color)
img.Set(center.X+x, center.Y-y, color)
img.Set(center.X+y, center.Y+x, color)
img.Set(center.X+y, center.Y-x, color)
img.Set(center.X-x, center.Y-y, color)
img.Set(center.X-y, center.Y-x, color)
img.Set(center.X-x, center.Y+y, color)
img.Set(center.X-y, center.Y+x, color)
y++
if radiusError < 0 {
radiusError += 2*y + 1
} else {
x--
radiusError += 2*(y-x) + 1
}
}
}
When you run this program, it will create a new 200x200 pixel image and draw a red rectangle and a blue circle on it. The resulting image will be saved as output.png
in the current directory.