Currently, I'm trying to transform an existing C# project to GoLang. The project takes an XML file which contains a bunch of coordinates and draws them on an image.
In C# the code to draw a rectangle on an image is the following:
public void DrawRectangle(Graphics graphics, RectangleShape rectangle)
{
using (var drawingPen = new Pen(Color.Black))
{
graphics.DrawRectangle(
drawingPen,
rectangle.StartX,
rectangle.StartY,
rectangle.Width,
rectangle.Height);
}
}
A rectangle is defined by the following class:
internal sealed class RectangleShape
{
internal RectangleShape(float startX, float startY, float width, float height)
{
this.StartX = startX;
this.StartY = startY;
this.Width = width;
this.Height = height;
}
internal float StartX { get; }
internal float StartY { get; }
internal float Width { get; }
internal float Height { get; }
}
It means that C# is able to draw a rectangle on an image using coordinates that are defined as float
.
Now, I'm trying to transform the code to GoLang where I'm drawing a rectangle with the following code:
// DrawRect draws a rectangle with the given dimensions on the given image.
func DrawRect(img *image.RGBA, rect Rectangle) {
endX := rect.X + rect.Width
endY := rect.Y + rect.Height
drawHLine(img, rect.X, rect.Y, endX)
drawHLine(img, rect.Y, endY, endX)
drawVLine(img, rect.Y, rect.X, endY)
drawVLine(img, rect.Y, endX, endY)
}
// PRIVATE: drawHLine draws a horizontal line with the given coordinates on the given image.
func drawHLine(img *image.RGBA, startX, y, endX float32) {
col := color.RGBA{0x00, 0x00, 0x00, 0xff}
for ; startX <= endX; startX++ {
img.Set(startX, y, col)
}
}
// PRIVATE: drawVLine draws a vertical line with the given coordinates on the given image.
func drawVLine(img *image.RGBA, startY, x, endY float32) {
col := color.RGBA{0x00, 0x00, 0x00, 0xff}
for ; startY <= endY; startY++ {
img.Set(x, startY, col)
}
}
The rectangle is defined with the following struct:
// Rectangle represents a rectangular shape.
type Rectangle struct {
X float32
Y float32
Width float32
Height float32
}
The sample in Go does not work because the Set
function on an image has the following structure:
func (p *RGBA) Set(x, y int, c color.Color) {
Is there any way how Go can work with float
parameters to draw a rectangle on an image?