gg

package module
v0.0.0-...-1c0905f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2023 License: MIT Imports: 25 Imported by: 0

README

Go Graphics

gg is a library for rendering 2D graphics in pure Go.

Stars

Installation

go get -u github.com/fogleman/gg

Alternatively, you may use gopkg.in to grab a specific major-version:

go get -u gopkg.in/fogleman/gg.v1

Documentation

Hello, Circle!

Look how easy!

package main

import "github.com/fogleman/gg"

func main() {
    dc := gg.NewContext(1000, 1000)
    dc.DrawCircle(500, 500, 400)
    dc.SetRGB(0, 0, 0)
    dc.Fill()
    dc.SavePNG("out.png")
}

Examples

There are lots of examples included. They're mostly for testing the code, but they're good for learning, too.

Examples

Creating Contexts

There are a few ways of creating a context.

NewContext(width, height int) *Context
NewContextForImage(im image.Image) *Context
NewContextForRGBA(im *image.RGBA) *Context

Drawing Functions

Ever used a graphics library that didn't have functions for drawing rectangles or circles? What a pain!

DrawPoint(x, y, r float64)
DrawLine(x1, y1, x2, y2 float64)
DrawRectangle(x, y, w, h float64)
DrawRoundedRectangle(x, y, w, h, r float64)
DrawCircle(x, y, r float64)
DrawArc(x, y, r, angle1, angle2 float64)
DrawEllipse(x, y, rx, ry float64)
DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)
DrawRegularPolygon(n int, x, y, r, rotation float64)
DrawImage(im image.Image, x, y int)
DrawImageAnchored(im image.Image, x, y int, ax, ay float64)
SetPixel(x, y int)

MoveTo(x, y float64)
LineTo(x, y float64)
QuadraticTo(x1, y1, x2, y2 float64)
CubicTo(x1, y1, x2, y2, x3, y3 float64)
ClosePath()
ClearPath()
NewSubPath()

Clear()
Stroke()
Fill()
StrokePreserve()
FillPreserve()

It is often desired to center an image at a point. Use DrawImageAnchored with ax and ay set to 0.5 to do this. Use 0 to left or top align. Use 1 to right or bottom align. DrawStringAnchored does the same for text, so you don't need to call MeasureString yourself.

Text Functions

It will even do word wrap for you!

DrawString(s string, x, y float64)
DrawStringAnchored(s string, x, y, ax, ay float64)
DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align)
MeasureString(s string) (w, h float64)
MeasureMultilineString(s string, lineSpacing float64) (w, h float64)
WordWrap(s string, w float64) []string
SetFontFace(fontFace font.Face)
LoadFontFace(path string, points float64) error

Color Functions

Colors can be set in several different ways for your convenience.

SetRGB(r, g, b float64)
SetRGBA(r, g, b, a float64)
SetRGB255(r, g, b int)
SetRGBA255(r, g, b, a int)
SetColor(c color.Color)
SetHexColor(x string)

Stroke & Fill Options

SetLineWidth(lineWidth float64)
SetLineCap(lineCap LineCap)
SetLineJoin(lineJoin LineJoin)
SetDash(dashes ...float64)
SetDashOffset(offset float64)
SetFillRule(fillRule FillRule)

Gradients & Patterns

gg supports linear, radial and conic gradients and surface patterns. You can also implement your own patterns.

SetFillStyle(pattern Pattern)
SetStrokeStyle(pattern Pattern)
NewSolidPattern(color color.Color)
NewLinearGradient(x0, y0, x1, y1 float64)
NewRadialGradient(x0, y0, r0, x1, y1, r1 float64)
NewConicGradient(cx, cy, deg float64)
NewSurfacePattern(im image.Image, op RepeatOp)

Transformation Functions

Identity()
Translate(x, y float64)
Scale(x, y float64)
Rotate(angle float64)
Shear(x, y float64)
ScaleAbout(sx, sy, x, y float64)
RotateAbout(angle, x, y float64)
ShearAbout(sx, sy, x, y float64)
TransformPoint(x, y float64) (tx, ty float64)
InvertY()

It is often desired to rotate or scale about a point that is not the origin. The functions RotateAbout, ScaleAbout, ShearAbout are provided as a convenience.

InvertY is provided in case Y should increase from bottom to top vs. the default top to bottom.

Stack Functions

Save and restore the state of the context. These can be nested.

Push()
Pop()

Clipping Functions

Use clipping regions to restrict drawing operations to an area that you defined using paths.

Clip()
ClipPreserve()
ResetClip()
AsMask() *image.Alpha
SetMask(mask *image.Alpha)
InvertMask()

Helper Functions

Sometimes you just don't want to write these yourself.

Radians(degrees float64) float64
Degrees(radians float64) float64
LoadImage(path string) (image.Image, error)
LoadPNG(path string) (image.Image, error)
SavePNG(path string, im image.Image) error

Separator

Another Example

See the output of this example below.

package main

import "github.com/fogleman/gg"

func main() {
	const S = 1024
	dc := gg.NewContext(S, S)
	dc.SetRGBA(0, 0, 0, 0.1)
	for i := 0; i < 360; i += 15 {
		dc.Push()
		dc.RotateAbout(gg.Radians(float64(i)), S/2, S/2)
		dc.DrawEllipse(S/2, S/2, S*7/16, S/8)
		dc.Fill()
		dc.Pop()
	}
	dc.SavePNG("out.png")
}

Ellipses

Documentation

Overview

Package gg provides a simple API for rendering 2D graphics in pure Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Degrees

func Degrees(radians float64) float64

Degrees converts an angle in radians to degrees.

func EncodeGIF

func EncodeGIF(w io.Writer, im []image.Image, delay int) error

EncodeGIF encodes an image as a GIF and writes it to the provided io.Writer with an optional delay between frames.

func EncodeJPG

func EncodeJPG(w io.Writer, im image.Image, opt *jpeg.Options) error

EncodeJPG encodes an image as a JPEG and writes it to the provided io.Writer with optional encoding options.

func EncodePNG

func EncodePNG(w io.Writer, im image.Image) error

EncodePNG encodes an image as a PNG and writes it to the provided io.Writer.

func FontNewFace

func FontNewFace(f *opentype.Font, points float64, hinting ...font.Hinting) (font.Face, error)

FontNewFace creates a font face from a parsed *opentype.Font with the specified point size and hinting.

func FontParse

func FontParse(raw []byte) (*opentype.Font, error)

FontParse parses TrueType or OpenType font data from a byte slice and returns an *opentype.Font.

func FontParseCollection

func FontParseCollection(raw []byte, i ...int) (*opentype.Font, error)

FontParseCollection parses a TrueType or OpenType font collection from a byte slice and returns an *opentype.Font.

func ImageToRGBA

func ImageToRGBA(src image.Image) *image.RGBA

ImageToRGBA converts an image.Image to an *image.RGBA by creating a new *image.RGBA with the same bounds as the source image and copying the image content into it.

func LoadFontFace

func LoadFontFace(path string, points float64) (font.Face, error)

LoadFontFace loads a font face from a TrueType or OpenType font file at the specified file path and returns it as a font.Face with the specified point size.

func LoadFontFaceFromBytes

func LoadFontFaceFromBytes(raw []byte, points float64) (font.Face, error)

LoadFontFaceFromBytes creates a font face from a byte slice containing TrueType or OpenType font data, and sets the specified point size.

func LoadFontFaceFromFS

func LoadFontFaceFromFS(fsys fs.FS, path string, points float64) (font.Face, error)

LoadFontFaceFromFS loads a font face from a TrueType or OpenType font file at the specified file path within a file system (fs.FS) and returns it as a font.Face with the specified point size.

func LoadFontFaceFromReader

func LoadFontFaceFromReader(r io.Reader, points float64) (font.Face, error)

LoadFontFaceFromReader loads a font face from a TrueType or OpenType font file at the specified io.Reader and returns it as a font.Face with the specified point size.

func LoadImage

func LoadImage(path string) (image.Image, error)

LoadImage loads an image from the specified file path and returns it as an image.Image. It opens the file, decodes the image, and returns the decoded image.

func LoadImageFromBytes

func LoadImageFromBytes(raw []byte) (image.Image, error)

LoadImageFromBytes decodes an image from a byte slice and returns it as an image.Image.

func LoadImageFromFS

func LoadImageFromFS(fsys fs.FS, path string) (image.Image, error)

LoadImageFromFS loads an image from the file system provided by a file system (fs.FS) and returns it as an image.Image. It opens the specified file within the file system, decodes the image, and returns the decoded image.

func LoadImageFromReader

func LoadImageFromReader(r io.Reader) (image.Image, error)

LoadImageFromReader loads an image from an io.Reader and returns it as an image.Image. It decodes the image, and returns the decoded image.

func LoadJPG

func LoadJPG(path string) (image.Image, error)

LoadJPG loads a JPEG image from the specified file path and returns it as an image.Image. It opens the file, decodes the JPEG image, and returns the decoded image.

func LoadJPGFromBytes

func LoadJPGFromBytes(raw []byte) (image.Image, error)

LoadJPGFromBytes decodes a JPEG image from a byte slice and returns it as an image.Image.

func LoadJPGFromFS

func LoadJPGFromFS(fsys fs.FS, path string) (image.Image, error)

LoadJPGFromFS loads a JPEG image from the specified file path within a file system (fs.FS) and returns it as an image.Image. It opens the specified file within the file system, decodes the JPEG image, and returns the decoded image.

func LoadJPGFromReader

func LoadJPGFromReader(r io.Reader) (image.Image, error)

LoadJPGFromReader loads a JPEG image from an io.Reader and returns it as an image.Image. It decodes the JPEG image, and returns the decoded image.

func LoadPNG

func LoadPNG(path string) (image.Image, error)

LoadPNG loads a PNG image from the specified file path and returns it as an image.Image. It opens the file, decodes the PNG image, and returns the decoded image.

func LoadPNGFromBytes

func LoadPNGFromBytes(raw []byte) (image.Image, error)

LoadPNGFromBytes decodes a PNG image from a byte slice and returns it as an image.Image.

func LoadPNGFromFS

func LoadPNGFromFS(fsys fs.FS, path string) (image.Image, error)

LoadPNGFromFS loads a PNG image from the specified file path within a file system (fs.FS) and returns it as an image.Image. It opens the specified file within the file system, decodes the PNG image, and returns the decoded image.

func LoadPNGFromReader

func LoadPNGFromReader(r io.Reader) (image.Image, error)

LoadPNGFromReader loads a PNG image from an io.Reader and returns it as an image.Image. It decodes the PNG image, and returns the decoded image.

func ParseHexColor

func ParseHexColor(x string) (r, g, b, a int)

ParseHexColor parses a hexadecimal color string (e.g., "#RGB" or "#RRGGBB" or "#RRGGBBAA") and returns the corresponding red (r), green (g), blue (b), and alpha (a) values. If the alpha component is not provided, it defaults to 255 (fully opaque).

func RGBAToImage

func RGBAToImage(src *image.RGBA) image.Image

RGBAToImage converts an *image.RGBA to an image.Image by creating a new image.Image with the same bounds as the source image and copying the image content into it.

func Radians

func Radians(degrees float64) float64

Radians converts an angle in degrees to radians.

func SaveGIF

func SaveGIF(path string, im []image.Image, delay int) error

SaveGIF saves an image as a GIF file at the specified path with an optional delay between frames.

func SaveJPG

func SaveJPG(path string, im image.Image, quality ...int) error

SaveJPG saves an image as a JPEG file at the specified path with an optional quality setting.

func SavePNG

func SavePNG(path string, im image.Image) error

SavePNG saves an image as a PNG file at the specified path.

Types

type Align

type Align int

Align defines text alignment options for text rendering.

const (
	AlignLeft   Align = iota // Left alignment for text rendering.
	AlignCenter              // Center alignment for text rendering.
	AlignRight               // Right alignment for text rendering.
)

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context represents a 2D rendering context used for drawing operations.

func NewContext

func NewContext(width, height int) *Context

NewContext creates a new rendering context with the specified width and height.

This function initializes a new rendering context with the provided 'width' and 'height' dimensions. The context is used for performing 2D drawing operations, including path rendering, text rendering, and manipulation of the rendering state.

func NewContextForImage

func NewContextForImage(im image.Image) *Context

NewContextForImage creates a new rendering context based on an existing image.Image.

This function initializes a new rendering context using the dimensions and content of the provided 'im' image. The context is used for performing 2D drawing operations, including path rendering, text rendering, and manipulation of the rendering state.

func NewContextForRGBA

func NewContextForRGBA(im *image.RGBA) *Context

NewContextForRGBA prepares a context for rendering onto the specified image. No copy is made.

func (*Context) AppendFrame

func (dc *Context) AppendFrame()

AppendFrame appends the current context image to the frames slice.

This method copies the current context image and appends it to the frames slice. This method is used for creating animated image.

func (*Context) AsMask

func (dc *Context) AsMask() *image.Alpha

AsMask converts the context's image to a mask.

This method converts the context's image to a mask, which can be used for masking in future rendering operations. The original image is copied to create the mask, and the mask is returned.

func (*Context) Clear

func (dc *Context) Clear()

Clear sets the entire context's image to a uniform color, effectively clearing the rendering area.

This method fills the entire context's image with the specified uniform color, effectively clearing the rendering area. The uniform color is set to the context's current color. The Clear operation overwrites any existing content in the image with the specified color, making the entire image uniform.

func (*Context) ClearPath

func (dc *Context) ClearPath()

ClearPath clears both the fill and stroke paths, and resets the current point.

This method clears both the fill and stroke paths and resets the current point, effectively starting a new subpath.

func (*Context) Clip

func (dc *Context) Clip()

Clip applies the clip operation to the current path and clears the path.

This method applies the clip operation to the current path and clears the path. It uses the ClipPreserve method to define the clipping area for future rendering. After applying the clip, the current path is cleared.

func (*Context) ClipPreserve

func (dc *Context) ClipPreserve()

ClipPreserve applies the clip operation to the current path, preserving the path for future rendering.

This method applies the clip operation to the current path and preserves the path for future rendering. It creates a mask using the current path, and if a mask already exists, it combines the new mask with the existing one. The mask is used to define the clipping area for future rendering.

func (*Context) ClosePath

func (dc *Context) ClosePath()

ClosePath closes the current subpath by adding a straight line to the starting point.

This method closes the current subpath by appending a straight line segment from the current point to the starting point of the subpath. If there is no current subpath, this method has no effect.

func (*Context) CubicTo

func (dc *Context) CubicTo(x1, y1, x2, y2, x3, y3 float64)

CubicTo adds a cubic Bézier curve segment to the current subpath.

This method appends a cubic Bézier curve segment defined by the current point (start point) and three control points (x1, y1, x2, y2, x3, y3) to both the fill and stroke paths. If there is no current subpath, this method behaves as if MoveTo() was called with the starting point coordinates (x1, y1).

func (*Context) DrawArc

func (dc *Context) DrawArc(x, y, r, angle1, angle2 float64)

DrawArc draws an arc within the specified parameters.

This method draws an arc within a circle with center (x, y) and radius 'r' starting at 'angle1' and ending at 'angle2' (in radians). The arc is drawn as a series of connected line segments.

func (*Context) DrawCircle

func (dc *Context) DrawCircle(x, y, r float64)

DrawCircle draws a circle centered at (x, y) with the specified radius 'r'.

This method draws a circle with center at (x, y) and radius 'r'. The circle is drawn as a series of connected line segments.

func (*Context) DrawEllipse

func (dc *Context) DrawEllipse(x, y, rx, ry float64)

DrawEllipse draws an ellipse within the specified bounding box.

This method draws an ellipse within the bounding box defined by the center point (x, y) and the radii 'rx' and 'ry'. The ellipse is drawn as a series of connected line segments that approximate the ellipse shape.

func (*Context) DrawEllipticalArc

func (dc *Context) DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)

DrawEllipticalArc draws a series of connected line segments to approximate an elliptical arc.

This method approximates an elliptical arc within the specified bounding box defined by (x, y), width 'rx', and height 'ry'. The arc is drawn between the angles 'angle1' and 'angle2'.

func (*Context) DrawImage

func (dc *Context) DrawImage(im image.Image, x, y int)

DrawImage draws an image at the specified (x, y) coordinates.

This method draws the given image at the specified (x, y) coordinates in the context's image. The top-left corner of the image will be positioned at the (x, y) coordinates.

func (*Context) DrawImageAnchored

func (dc *Context) DrawImageAnchored(im image.Image, x, y int, ax, ay float64)

DrawImageAnchored draws an image anchored at the specified (x, y) coordinates. The anchor point is x - w * ax, y - h * ay, where w, h is the size of the image.

This method draws the given image anchored at the specified (x, y) coordinates in the context's image. The anchor point (ax, ay) determines the relative position within the image that aligns with the (x, y) coordinates. For example, (0, 0) represents the top-left corner of the image, (0.5, 0.5) represents the center, and (1, 1) represents the bottom-right corner.

func (*Context) DrawLine

func (dc *Context) DrawLine(x1, y1, x2, y2 float64)

DrawLine draws a straight line segment between two points.

This method draws a straight line segment between the points (x1, y1) and (x2, y2).

func (*Context) DrawPoint

func (dc *Context) DrawPoint(x, y, r float64)

DrawPoint draws a filled circle at the specified point.

This method draws a filled circle with the specified radius (r) centered at the coordinates (x, y).

func (*Context) DrawRectangle

func (dc *Context) DrawRectangle(x, y, w, h float64)

DrawRectangle draws a filled rectangle at the specified coordinates with the given width and height.

This method draws a filled rectangle with its top-left corner at coordinates (x, y), a width of 'w', and a height of 'h'.

func (*Context) DrawRegularPolygon

func (dc *Context) DrawRegularPolygon(n int, x, y, r, rotation float64)

DrawRegularPolygon draws a regular polygon with 'n' sides.

This method draws a regular polygon with 'n' sides, centered at (x, y) with a given radius 'r'. The 'rotation' parameter specifies the initial rotation angle. The polygon is drawn as a series of connected line segments.

func (*Context) DrawRoundedRectangle

func (dc *Context) DrawRoundedRectangle(x, y, w, h, r float64)

DrawRoundedRectangle draws a filled rounded rectangle with the specified coordinates, dimensions, and corner radius.

This method draws a filled rounded rectangle with its top-left corner at coordinates (x, y), a width of 'w', a height of 'h', and rounded corners with a radius of 'r'.

func (*Context) DrawString

func (dc *Context) DrawString(s string, x, y float64)

DrawString renders a text string at the specified coordinates.

This method renders the given text string `s` at the specified (x, y) coordinates on the context's image. The text is rendered using the current font face, color, and other text rendering settings of the context. The (x, y) coordinates represent the baseline position for rendering the text.

func (*Context) DrawStringAnchored

func (dc *Context) DrawStringAnchored(s string, x, y, ax, ay float64)

DrawStringAnchored renders a text string anchored at the specified coordinates.

This method renders the given text string `s` anchored at the specified (x, y) coordinates on the context's image. The anchor point is determined by the `ax` (X-axis) and `ay` (Y-axis) values, which represent the relative position within the text bounding box. The text is rendered using the current font face, color, and other text rendering settings of the context.

func (*Context) DrawStringWrapped

func (dc *Context) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align)

DrawStringWrapped renders a text string wrapped within a specified width.

This method renders the given text string `s` wrapped within the specified `width` while anchored at the (x, y) coordinates. The text is wrapped into multiple lines to fit the given width. The `ax` (X-axis) and `ay` (Y-axis) values determine the anchor point's relative position within the text bounding box, and the `lineSpacing` controls the vertical spacing between lines. The `align` parameter specifies the horizontal alignment of the text.

func (*Context) Fill

func (dc *Context) Fill()

Fill applies the fill operation to the current path and clears the path.

This method applies the fill operation to the current path and clears the path. It uses the FillPreserve method to render the fill and then clears the path, making it ready for further path construction.

func (*Context) FillPreserve

func (dc *Context) FillPreserve()

FillPreserve applies the fill operation to the current path, preserving the path for future rendering.

This method applies the fill operation to the current path and preserves the path for future rendering. It selects the appropriate painter based on the fill pattern and the presence of a mask. It then calls the fill method to render the fill. After the fill is applied, the current path remains intact.

func (*Context) FontHeight

func (dc *Context) FontHeight() float64

FontHeight returns the height of the currently set font face.

This method returns the height of the font face currently set for text rendering. The height is measured in points.

func (*Context) Frames

func (dc *Context) Frames() []image.Image

Frames returns the frames slice.

This method returns the frames slice. It is used for creating animated image.

func (*Context) GetCurrentPoint

func (dc *Context) GetCurrentPoint() (Point, bool)

GetCurrentPoint returns the current point (cursor position) in the rendering context.

This method retrieves the current cursor position in the rendering context. The current point represents the location where the most recent drawing operation ended or where the cursor was explicitly positioned.

func (*Context) Height

func (dc *Context) Height() int

Height returns the height of the rendering context.

This method retrieves the height of the rendering context in pixels.

func (*Context) Identity

func (dc *Context) Identity()

Identity resets the current transformation matrix to the identity matrix.

This method sets the transformation matrix of the drawing context to the identity matrix, effectively removing any prior transformations.

func (*Context) Image

func (dc *Context) Image() image.Image

Image returns the image.RGBA associated with the rendering context.

This method retrieves the image.RGBA associated with the rendering context. The image.RGBA represents the canvas or target image where the 2D drawing operations are performed and rendered.

func (*Context) InvertMask

func (dc *Context) InvertMask()

InvertMask inverts the current mask or creates a new one if none exists.

This method inverts the current mask if one exists. If no mask is set, it creates a new alpha mask and inverts it. The inverted mask can be used for masking in future rendering operations.

func (*Context) InvertY

func (dc *Context) InvertY()

InvertY inverts the Y-axis of the current transformation.

This method inverts the Y-axis of the current drawing context. It effectively flips the vertical orientation of subsequent drawings.

func (*Context) LineTo

func (dc *Context) LineTo(x, y float64)

LineTo adds a straight line segment to the current subpath.

This method appends a straight line segment from the current point to the specified coordinates (x, y) to both the fill and stroke paths. If there is no current subpath, this method behaves as if MoveTo() was called with the same coordinates.

func (*Context) LoadFontFace

func (dc *Context) LoadFontFace(path string, points float64) error

LoadFontFace loads a font face from a file and sets it for text rendering.

This method loads a font face from the specified file path and sets it for rendering text. The `points` parameter determines the font size in points.

func (*Context) LoadFontFaceFromBytes

func (dc *Context) LoadFontFaceFromBytes(raw []byte, points float64) error

LoadFontFaceFromBytes loads a font face from raw font data and sets it for text rendering.

This method loads a font face from raw font data provided as a byte slice and sets it for rendering text. The `points` parameter determines the font size in points.

func (*Context) LoadFontFaceFromFS

func (dc *Context) LoadFontFaceFromFS(fsys fs.FS, path string, points float64) error

LoadFontFaceFromFS loads a font face from a file system (fs.FS) and sets it for text rendering.

This method loads a font face from the file system (fs.FS) and sets it for rendering text. The `points` parameter determines the font size in points.

func (*Context) LoadFontFaceFromReader

func (dc *Context) LoadFontFaceFromReader(r io.Reader, points float64) error

LoadFontFaceFromReader loads a font face from an io.Reader and sets it for text rendering.

This method loads a font face from the specified io.Reader and sets it for rendering text. The `points` parameter determines the font size in points.

func (*Context) MeasureMultilineString

func (dc *Context) MeasureMultilineString(s string, lineSpacing float64) (width, height float64)

MeasureMultilineString measures the width and height of a multiline text string.

This method calculates the dimensions of a multiline text string `s`, taking into account the specified `lineSpacing` factor for vertical line spacing. It returns the width and height of the multiline text in pixels.

func (*Context) MeasureString

func (dc *Context) MeasureString(s string) (w, h float64)

MeasureString measures the width and height of a single-line text string.

This method calculates the dimensions of a single-line text string `s` and returns its width and the standard line height (font height).

func (*Context) MoveTo

func (dc *Context) MoveTo(x, y float64)

MoveTo starts a new subpath at the specified point (x, y).

This method begins a new subpath in the rendering context with the current point set to the specified coordinates (x, y). If there was a previous subpath and the current point was set, this method adds that point to the fill path and starts the stroke path from the new point.

func (*Context) NewSubPath

func (dc *Context) NewSubPath()

NewSubPath starts a new subpath without adding any line segments.

This method begins a new subpath without adding any line segments to it. If there was a previous subpath and the current point was set, this method adds that point to the fill path.

func (*Context) Pop

func (dc *Context) Pop()

Pop restores the drawing context to a previously saved state from the context stack.

This method pops the topmost state from the context stack and restores the drawing context to this saved state. It effectively reverts the current drawing state to a previous state that was saved using the Push method.

func (*Context) Push

func (dc *Context) Push()

Push saves the current drawing context by creating a copy of it and pushing it onto the context stack.

This method saves the current state of the drawing context by creating a copy of it and pushing it onto the context stack. You can later restore this state using the Pop method.

func (*Context) QuadraticTo

func (dc *Context) QuadraticTo(x1, y1, x2, y2 float64)

QuadraticTo adds a quadratic Bézier curve segment to the current subpath.

This method appends a quadratic Bézier curve segment defined by the current point (start point) and two control points (x1, y1 and x2, y2) to both the fill and stroke paths. If there is no current subpath, this method behaves as if MoveTo() was called with the starting point coordinates (x1, y1).

func (*Context) ResetClip

func (dc *Context) ResetClip()

ResetClip clears the current clipping mask.

This method clears the current clipping mask, allowing for unrestricted rendering. It effectively removes any clipping effects applied by previous Clip or ClipPreserve operations.

func (*Context) Rotate

func (dc *Context) Rotate(angle float64)

Rotate applies a rotation transformation to the current transformation matrix.

This method rotates the drawing context by the specified angle in radians. It modifies the current transformation matrix to reflect the rotation.

func (*Context) RotateAbout

func (dc *Context) RotateAbout(angle, x, y float64)

RotateAbout applies a rotation transformation about a specified point.

This method rotates the drawing context by the specified angle in radians around the point (x, y). It is equivalent to translating the context to the center of rotation, rotating it, and then translating it back to its original position.

func (*Context) Scale

func (dc *Context) Scale(x, y float64)

Scale applies a scaling transformation to the current matrix.

This method scales the drawing context by the specified horizontal (x) and vertical (y) scaling factors. It modifies the current transformation matrix to reflect the scaling.

func (*Context) ScaleAbout

func (dc *Context) ScaleAbout(sx, sy, x, y float64)

ScaleAbout applies a scaling transformation about a specified point.

This method scales the drawing context by the specified horizontal (sx) and vertical (sy) scaling factors around the point (x, y). It is equivalent to translating the context to the center of scaling, scaling it, and then translating it back to its original position.

func (*Context) SetColor

func (dc *Context) SetColor(c color.Color)

SetColor sets the fill and stroke color of the rendering context to the specified color.

This method sets both the fill and stroke colors of the rendering context to the specified color 'c'. The 'c' parameter should be a color.Color value representing the desired color.

func (*Context) SetDash

func (dc *Context) SetDash(dashes ...float64)

SetDash sets the dash pattern for stroking lines.

This method allows you to set a custom dash pattern for stroking lines. You can provide a sequence of 'dashes' values to specify the lengths of dashes and gaps between them. For example, to create a dashed line with a 10-pixel dash followed by a 5-pixel gap, you can call SetDash(10, 5).

func (*Context) SetDashOffset

func (dc *Context) SetDashOffset(offset float64)

SetDashOffset sets the offset for the dash pattern.

This method allows you to set the offset (phase) for the dash pattern when stroking lines. The 'offset' value determines where the dash pattern starts along the path. You can specify the 'offset' in units of the current line width.

func (*Context) SetFillRule

func (dc *Context) SetFillRule(fillRule FillRule)

SetFillRule sets the fill rule for determining the interior of filled shapes.

This method allows you to set the fill rule for determining the interior of filled shapes. You can choose from two predefined fill rules: FillRuleWinding and FillRuleEvenOdd.

func (*Context) SetFillRuleEvenOdd

func (dc *Context) SetFillRuleEvenOdd()

SetFillRuleEvenOdd sets the fill rule to Even-Odd for determining the interior of filled shapes.

This method sets the fill rule to Even-Odd for determining the interior of filled shapes. In this rule, a point is considered inside a shape if a ray from the point in any direction crosses an odd number of times with the shape's boundary.

func (*Context) SetFillRuleWinding

func (dc *Context) SetFillRuleWinding()

SetFillRuleWinding sets the fill rule to Winding for determining the interior of filled shapes.

This method sets the fill rule to Winding for determining the interior of filled shapes. In this rule, a point is considered inside a shape if a ray from the point in any direction crosses an odd number of times with the shape's boundary.

func (*Context) SetFillStyle

func (dc *Context) SetFillStyle(pattern Pattern)

SetFillStyle sets the fill style of the rendering context.

This method allows you to set the fill style of the rendering context using the specified 'pattern'. The 'pattern' can be any implementation of the Pattern interface, such as SolidPattern, Gradient, or TexturePattern. If a SolidPattern is used, the method also updates the current 'color' of the context.

func (*Context) SetFontFace

func (dc *Context) SetFontFace(fontFace font.Face)

SetFontFace sets the font face for text rendering.

This method sets the font face for rendering text. The provided `fontFace` is used for subsequent text operations. You can obtain a font face using the `LoadFontFace` or related methods.

func (*Context) SetHexColor

func (dc *Context) SetHexColor(x string)

SetHexColor sets the fill and stroke color of the rendering context using a hexadecimal color string.

This method sets both the fill and stroke colors of the rendering context to the colors specified in the hexadecimal color string 'x'. The 'x' parameter should be a string in the format "#RGB" or "#RRGGBB" or "#RRGGBBAA".

func (*Context) SetInterpolator

func (dc *Context) SetInterpolator(interp draw.Interpolator)

SetInterpolator sets the drawing interpolator for the context.

This method allows you to set a custom drawing interpolator for the context. The interpolator is responsible for determining how paths and shapes are transformed and rendered, affecting the quality and smoothness of the output. Providing a nil interpolator will result in a panic.

func (*Context) SetLineCap

func (dc *Context) SetLineCap(lineCap LineCap)

SetLineCap sets the line cap style for the end of stroked lines.

This method allows you to set the line cap style for the ends of stroked lines. You can choose from three predefined styles: LineCapRound, LineCapButt, and LineCapSquare.

func (*Context) SetLineCapButt

func (dc *Context) SetLineCapButt()

SetLineCapButt sets the line cap style to Butt for the end of stroked lines.

This method sets the line cap style to Butt for the ends of stroked lines, which results in flat line endings.

func (*Context) SetLineCapRound

func (dc *Context) SetLineCapRound()

SetLineCapRound sets the line cap style to Round for the end of stroked lines.

This method sets the line cap style to Round for the ends of stroked lines, which results in rounded line endings.

func (*Context) SetLineCapSquare

func (dc *Context) SetLineCapSquare()

SetLineCapSquare sets the line cap style to Square for the end of stroked lines.

This method sets the line cap style to Square for the ends of stroked lines, which results in square line endings.

func (*Context) SetLineJoin

func (dc *Context) SetLineJoin(lineJoin LineJoin)

SetLineJoin sets the line join style for the intersection of stroked lines.

This method allows you to set the line join style for the intersections of stroked lines. You can choose from two predefined styles: LineJoinRound and LineJoinBevel.

func (*Context) SetLineJoinBevel

func (dc *Context) SetLineJoinBevel()

SetLineJoinBevel sets the line join style to Bevel for the intersection of stroked lines.

This method sets the line join style to Bevel for the intersections of stroked lines, which results in beveled intersections.

func (*Context) SetLineJoinRound

func (dc *Context) SetLineJoinRound()

SetLineJoinRound sets the line join style to Round for the intersection of stroked lines.

This method sets the line join style to Round for the intersections of stroked lines, which results in rounded intersections.

func (*Context) SetLineWidth

func (dc *Context) SetLineWidth(lineWidth float64)

SetLineWidth sets the line width for drawing operations.

This method allows you to set the line width for stroking lines and drawing shapes. The 'lineWidth' parameter specifies the width of lines in user space units (typically pixels).

func (*Context) SetMask

func (dc *Context) SetMask(mask *image.Alpha) error

SetMask sets the mask of the rendering context.

This method sets the mask of the rendering context to the specified image.Alpha mask. The mask size must match the size of the context's image. If the mask size does not match, an error is returned.

func (*Context) SetPixel

func (dc *Context) SetPixel(x, y int)

SetPixel sets the color of a single pixel at the specified coordinates.

This method sets the color of a single pixel at the given (x, y) coordinates in the context's image to the current color. It effectively paints a single pixel with the specified color.

func (*Context) SetRGB

func (dc *Context) SetRGB(r, g, b float64)

SetRGB sets the fill and stroke color of the rendering context to the specified RGB color using floating-point values.

This method sets both the fill and stroke colors of the rendering context to the specified RGB color using floating-point values in the range [0.0, 1.0]. The 'r', 'g', and 'b' parameters should represent the red, green, and blue components, and an alpha value of 1.0 (fully opaque) is used.

func (*Context) SetRGB255

func (dc *Context) SetRGB255(r, g, b int)

SetRGB255 sets the fill and stroke color of the rendering context to the specified RGB color using 8-bit values.

This method sets both the fill and stroke colors of the rendering context to the specified RGB color using 8-bit values for red, green, and blue. The 'r', 'g', and 'b' parameters should be integers in the range [0, 255], and an alpha value of 255 (fully opaque) is used.

func (*Context) SetRGBA

func (dc *Context) SetRGBA(r, g, b, a float64)

SetRGBA sets the fill and stroke color of the rendering context to the specified RGBA color using floating-point values.

This method sets both the fill and stroke colors of the rendering context to the specified RGBA color using floating-point values in the range [0.0, 1.0]. The 'r', 'g', 'b', and 'a' parameters should represent the red, green, blue, and alpha components, respectively.

func (*Context) SetRGBA255

func (dc *Context) SetRGBA255(r, g, b, a int)

SetRGBA255 sets the fill and stroke color of the rendering context to the specified RGBA color using 8-bit values.

This method sets both the fill and stroke colors of the rendering context to the specified RGBA color using 8-bit values for red, green, blue, and alpha. The 'r', 'g', 'b', and 'a' parameters should be integers in the range [0, 255].

func (*Context) SetStrokeStyle

func (dc *Context) SetStrokeStyle(pattern Pattern)

SetStrokeStyle sets the stroke style of the rendering context.

This method allows you to set the stroke style of the rendering context using the specified 'pattern'. The 'pattern' can be any implementation of the Pattern interface, such as SolidPattern, Gradient, or TexturePattern.

func (*Context) Shear

func (dc *Context) Shear(x, y float64)

Shear applies a shear transformation to the current transformation matrix.

This method shears the drawing context by the specified horizontal (x) and vertical (y) shear factors. It modifies the current transformation matrix to reflect the shear.

func (*Context) ShearAbout

func (dc *Context) ShearAbout(sx, sy, x, y float64)

ShearAbout applies a shear transformation about a specified point.

This method shears the drawing context by the specified horizontal (sx) and vertical (sy) shear factors around the point (x, y). It is equivalent to translating the context to the center of shearing, shearing it, and then translating it back to its original position.

func (*Context) Stroke

func (dc *Context) Stroke()

Stroke applies the stroke operation to the current path and clears the path.

This method applies the stroke operation to the current path and clears the path. It uses the StrokePreserve method to render the stroke and then clears the path, making it ready for further path construction.

func (*Context) StrokePreserve

func (dc *Context) StrokePreserve()

StrokePreserve applies the stroke operation to the current path, preserving the path for future rendering.

This method applies the stroke operation to the current path and preserves the path for future rendering. It selects the appropriate painter based on the stroke pattern and the presence of a mask. It then calls the stroke method to render the stroke. After the stroke is applied, the current path remains intact.

func (*Context) TransformPoint

func (dc *Context) TransformPoint(x, y float64) (tx, ty float64)

TransformPoint applies the current transformation matrix to the given (x, y) coordinates.

This method transforms the (x, y) coordinates using the current transformation matrix. It returns the transformed coordinates (tx, ty).

func (*Context) Translate

func (dc *Context) Translate(x, y float64)

Translate applies a translation to the current transformation matrix.

This method translates the drawing context by the specified horizontal (x) and vertical (y) amounts. It modifies the current transformation matrix to reflect the translation.

func (*Context) Width

func (dc *Context) Width() int

Width returns the width of the rendering context.

This method retrieves the width of the rendering context in pixels.

func (*Context) WordWrap

func (dc *Context) WordWrap(s string, w float64) []string

WordWrap wraps a text string to fit within a specified width.

This method takes a text string `s` and wraps it to fit within a given width `w`, breaking it into multiple lines as necessary to prevent text from exceeding the specified width. The result is returned as a slice of strings, each representing a wrapped line of text.

type FillRule

type FillRule int

FillRule specifies the fill rule for determining the interior of complex paths.

const (
	FillRuleWinding FillRule = iota // Winding fill rule for complex paths.
	FillRuleEvenOdd                 // Even-Odd fill rule for complex paths.
)

type Gradient

type Gradient interface {
	Pattern

	// AddColorStop appends a color stop to the linear gradient at the specified offset.
	//
	// This method adds a color stop to the gradient with the specified offset and color. Color stops
	// define where colors change within the gradient. The stops are sorted in ascending order based
	// on their offset values.
	AddColorStop(offset float64, color color.Color)
}

Gradient is an interface representing a gradient pattern that can be used to fill shapes with smooth color transitions.

func NewConicGradient

func NewConicGradient(cx, cy, deg float64) Gradient

NewConicGradient creates a new conic gradient with the specified center coordinates and rotation angle in degrees.

This function creates a conic gradient, which is a type of gradient that varies in color and smoothly rotates around a central point. You can define the center coordinates (cx, cy) and the rotation angle in degrees to control the gradient's appearance.

func NewLinearGradient

func NewLinearGradient(x0, y0, x1, y1 float64) Gradient

NewLinearGradient creates a new linear gradient pattern that spans from point (x0, y0) to point (x1, y1).

This function creates and returns a linear gradient pattern with the specified start and end points. Linear gradients fill an area with colors that transition from one point to another in a straight line.

func NewRadialGradient

func NewRadialGradient(x0, y0, r0, x1, y1, r1 float64) Gradient

NewRadialGradient creates a new radial gradient object based on the specified parameters.

This function initializes a radial gradient with the given circle coordinates and radii, which define the gradient's shape. The radial gradient will interpolate colors smoothly from one circle (defined by x0, y0, r0) to another circle (defined by x1, y1, r1).

type LineCap

type LineCap int

LineCap defines the possible line cap styles for drawing paths in a rendering context.

const (
	LineCapRound  LineCap = iota // Line cap style with round ends.
	LineCapButt                  // Line cap style with flat ends.
	LineCapSquare                // Line cap style with square ends.
)

type LineJoin

type LineJoin int

LineJoin defines the possible line join styles for connecting path segments in a rendering context.

const (
	LineJoinRound LineJoin = iota // Line join style with round connections.
	LineJoinBevel                 // Line join style with beveled connections.
)

type Matrix

type Matrix struct {
	XX, YX, XY, YY, X0, Y0 float64
}

Matrix represents a 2D transformation matrix with six components: XX, YX, XY, YY, X0, and Y0. This matrix is used to transform points, vectors, or perform various geometric transformations.

func Identity

func Identity() Matrix

Identity returns the identity matrix, which has no effect on transformations. The identity matrix is used as a starting point for geometric transformations.

func Rotate

func Rotate(angle float64) Matrix

Rotate returns a rotation matrix that rotates points by the specified angle (in radians) in a counterclockwise direction. This matrix is used to rotate objects in a 2D space.

func Scale

func Scale(x, y float64) Matrix

Scale returns a scaling matrix that scales points by the specified horizontal and vertical factors (x, y). This matrix is used to resize objects in a 2D space.

func Shear

func Shear(x, y float64) Matrix

Shear returns a shear matrix that shears points in the horizontal (x) and vertical (y) directions. This matrix is used to skew or slant objects in a 2D space.

func Translate

func Translate(x, y float64) Matrix

Translate returns a translation matrix that moves points by the specified horizontal and vertical offsets (x, y). This matrix is used to shift objects in a 2D space.

func (Matrix) Multiply

func (a Matrix) Multiply(b Matrix) Matrix

Multiply multiplies two matrices, a and b, and returns a new matrix that represents the combined transformation. This operation is used to apply a sequence of matrix transformations to points or objects in a 2D space.

func (Matrix) Rotate

func (a Matrix) Rotate(angle float64) Matrix

Rotate returns a new matrix resulting from applying a 2D rotation transformation by the given angle to matrix 'a'.

func (Matrix) Scale

func (a Matrix) Scale(x, y float64) Matrix

Scale returns a new matrix resulting from applying a 2D scaling transformation to matrix 'a'.

func (Matrix) Shear

func (a Matrix) Shear(x, y float64) Matrix

Shear returns a new matrix resulting from applying a 2D shear transformation by the given factors to matrix 'a'.

func (Matrix) TransformPoint

func (a Matrix) TransformPoint(x, y float64) (tx, ty float64)

TransformPoint applies the matrix transformation represented by 'a' to a 2D point (x, y). It returns the transformed point (tx, ty) after applying the matrix transformation.

func (Matrix) TransformVector

func (a Matrix) TransformVector(x, y float64) (tx, ty float64)

TransformVector applies the matrix transformation represented by 'a' to a 2D vector (x, y). It returns the transformed vector (tx, ty) after applying the matrix transformation.

func (Matrix) Translate

func (a Matrix) Translate(x, y float64) Matrix

Translate returns a new matrix resulting from applying a 2D translation by (x, y) to matrix 'a'.

type Pattern

type Pattern interface {
	ColorAt(x, y int) color.Color
}

Pattern is an interface representing a pattern used for filling areas with a repeating design. Implementations of this interface must provide the ability to sample and retrieve color information at specific coordinates (x, y) within the pattern.

func NewSolidPattern

func NewSolidPattern(color color.Color) Pattern

NewSolidPattern creates and returns a solid color pattern using the specified color.

func NewSurfacePattern

func NewSurfacePattern(im image.Image, op RepeatOp) Pattern

NewSurfacePattern creates a new surface pattern from the given image and repetition behavior.

type Point

type Point struct {
	X, Y float64
}

Point represents a two-dimensional point with X and Y coordinates.

func CubicBezier

func CubicBezier(x0, y0, x1, y1, x2, y2, x3, y3 float64) []Point

CubicBezier computes a series of points on a cubic Bézier curve defined by four control points.

The cubic Bézier curve is determined by the starting point (x0, y0), two control points (x1, y1) and (x2, y2), and the ending point (x3, y3). The function calculates 'n' equidistant points along the curve, where 'n' is determined by the cumulative length of the curve. If the calculated number of points is less than 4, it defaults to 4 points.

func QuadraticBezier

func QuadraticBezier(x0, y0, x1, y1, x2, y2 float64) []Point

QuadraticBezier computes a series of points on a quadratic Bézier curve defined by three control points.

The quadratic Bézier curve is determined by the starting point (x0, y0), a control point (x1, y1), and the ending point (x2, y2). The function calculates 'n' equidistant points along the curve, where 'n' is determined by the curve's total length. If the calculated number of points is less than 4, it defaults to 4 points.

func (Point) Distance

func (a Point) Distance(b Point) float64

Distance calculates the Euclidean distance between two points 'a' and 'b'.

func (Point) Fixed

func (a Point) Fixed() fixed.Point26_6

Fixed converts a Point to a fixed.Point26_6 representation.

func (Point) Interpolate

func (a Point) Interpolate(b Point, t float64) Point

Interpolate performs linear interpolation between two points 'a' and 'b' at a given parameter 't'.

type RepeatOp

type RepeatOp int

RepeatOp specifies how an image is repeated or tiled when it is painted onto a larger canvas.

const (
	RepeatBoth RepeatOp = iota // Repeat both indicates that the image is repeated both horizontally (X-axis) and vertically (Y-axis).
	RepeatX                    // Repeat x indicates that the image is repeated horizontally (X-axis) but not vertically (Y-axis).
	RepeatY                    // Repeat y indicates that the image is repeated vertically (Y-axis) but not horizontally (X-axis).
	RepeatNone                 // Repeat none indicates that the image is not repeated and is displayed only once.
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL