Documentation
¶
Overview ¶
Example (RichTextComprehensive) ¶
// 1. Setup Resources
gr, err := util.OpenFont("goregular")
if err != nil {
log.Fatal(err)
}
fontRegular := util.GetFontFace(24, 96, gr)
fontLarge := util.GetFontFace(40, 96, gr)
// Create a simple red box image for inline image demo
redBox := image.NewRGBA(image.Rect(0, 0, 30, 30))
draw.Draw(redBox, redBox.Bounds(), &image.Uniform{color.RGBA{255, 0, 0, 255}}, image.Point{}, draw.Src)
// Create a pebbles pattern for background demo using go-pattern
// Using Scatter for true overlapping geometry.
pat := pattern.NewScatter(
pattern.SetBounds(image.Rect(-100000, -100000, 100000, 100000)),
pattern.SetScatterFrequency(0.04), // Size control
pattern.SetScatterDensity(1.0), // Packed tight
pattern.SetScatterMaxOverlap(1),
pattern.SetSpaceColor(color.Transparent), // Transparent background!
pattern.SetScatterGenerator(func(u, v float64, hash uint64) (color.Color, float64) {
// Randomize size slightly
rSize := float64(hash&0xFF) / 255.0
radius := 12.0 + rSize*6.0 // 12 to 18 pixels radius
// Perturb the shape using simple noise (simulated by sin/cos of hash+angle)
// to make it "chipped" or irregular.
angle := math.Atan2(v, u)
dist := math.Sqrt(u*u + v*v)
// Simple radial noise
noise := math.Sin(angle*5+float64(hash%10)) * 0.1
noise += math.Cos(angle*13+float64(hash%7)) * 0.05
effectiveRadius := radius * (1.0 + noise)
if dist > effectiveRadius {
return color.Transparent, 0
}
// Stone Color: Lighter variations for readability
grey := 220 + int(hash%35)
col := color.RGBA{uint8(grey), uint8(grey), uint8(grey), 255}
// Shading (diffuse)
// Normal estimation for a flattened spheroid
nx := u / effectiveRadius
ny := v / effectiveRadius
nz := math.Sqrt(math.Max(0, 1.0-nx*nx-ny*ny))
// Light dir
lx, ly, lz := -0.5, -0.5, 0.7
lLen := math.Sqrt(lx*lx + ly*ly + lz*lz)
lx, ly, lz = lx/lLen, ly/lLen, lz/lLen
diffuse := math.Max(0, nx*lx+ny*ly+nz*lz)
// Apply shading
r := float64(col.R) * (0.1 + 0.9*diffuse)
g := float64(col.G) * (0.1 + 0.9*diffuse)
b := float64(col.B) * (0.1 + 0.9*diffuse)
// Soft edge anti-aliasing
alpha := 1.0
edgeDist := effectiveRadius - dist
if edgeDist < 1.0 {
alpha = edgeDist
}
// Use hash for random Z-ordering
z := float64(hash) / 18446744073709551615.0
return color.RGBA{
R: uint8(math.Min(255, r)),
G: uint8(math.Min(255, g)),
B: uint8(math.Min(255, b)),
A: uint8(alpha * 255),
}, z
}),
)
// Create a paper-like pattern for the page background
paper := image.NewRGBA(image.Rect(0, 0, 100, 100))
draw.Draw(paper, paper.Bounds(), &image.Uniform{color.RGBA{250, 250, 245, 255}}, image.Point{}, draw.Src)
// Add some noise/lines to make it obvious
for y := 0; y < 100; y += 20 {
draw.Draw(paper, image.Rect(0, y, 100, y+1), &image.Uniform{color.RGBA{220, 220, 210, 255}}, image.Point{}, draw.Over)
}
// 2. Build Rich Content
// We mix strings with option structs. The order matters (state machine).
args := []interface{}{
fontRegular,
"Standard text. ",
// Text Color
wordwrap.TextColor(color.RGBA{0, 0, 255, 255}),
"Blue Text. ",
wordwrap.TextColor(color.Black), // Reset
// Background Color (Highlight)
wordwrap.BgColor(color.RGBA{255, 255, 0, 255}),
"Yellow Background. ",
// Demonstrate Resetting Background to Transparent (should show paper pattern)
wordwrap.BgColor(color.Transparent),
"Back to Normal (should see paper). ",
// Optional: We can adds a helper for this later if needed
// wordwrap.NoBackground(),
// Scoped Styles using Group
wordwrap.Group{
Args: []interface{}{
wordwrap.TextColor(color.RGBA{0, 100, 0, 255}),
"Scoped Green Text. ",
wordwrap.BgColor(color.RGBA{220, 255, 220, 255}),
"Green on Light Green. ",
},
},
"Back to Normal. ",
"\n\n",
// Font Size Changes
fontLarge, "Large Text. ",
fontRegular, "Normal Text. ",
"\n\n",
// Effects: Underline, Strikethrough
"Text with ",
wordwrap.Group{
Args: []interface{}{
wordwrap.Underline(color.RGBA{255, 0, 0, 255}),
"Red Underline",
},
},
" and ",
wordwrap.Group{
Args: []interface{}{
wordwrap.Strikethrough(color.Black),
"Strikethrough",
},
},
".\n\n",
// Inline Images and Alignment
"Image aligned baseline: ",
wordwrap.ImageContent{Image: redBox},
" Text after.",
"\n",
"Image aligned Top: ",
wordwrap.Group{
Args: []interface{}{
wordwrap.Alignment(wordwrap.AlignTop),
wordwrap.ImageContent{Image: redBox},
},
},
" (Text Top).",
"\n",
"Image aligned Bottom: ",
wordwrap.Group{
Args: []interface{}{
wordwrap.Alignment(wordwrap.AlignBottom),
wordwrap.ImageContent{Image: redBox},
},
},
" (Text Bottom).",
"\n\n",
// Background Image Pattern
wordwrap.Group{
Args: []interface{}{
wordwrap.BgImage(pat, wordwrap.BgPositioningPassThrough),
"Text on Pattern Background. ",
fontLarge, "Even Large Text on Pattern.",
},
},
}
wrapper := wordwrap.NewRichWrapper(args...)
// 3. Layout with standard page constraints
result, err := wrapper.TextToSpecs(
wordwrap.Width(wordwrap.Fixed(800)), // Wider width as requested
wordwrap.Padding(20, color.Black),
// We don't set PageBackground here to avoid it overriding our manual draw if we relied on internal logic,
// but since we draw manually below, it's fine.
)
if err != nil {
log.Fatal(err)
}
// 4. Render
img := image.NewRGBA(image.Rect(0, 0, result.PageSize.X, result.PageSize.Y))
// Draw Paper Pattern as background (Tiled)
for y := 0; y < img.Bounds().Dy(); y += paper.Bounds().Dy() {
for x := 0; x < img.Bounds().Dx(); x += paper.Bounds().Dx() {
r := image.Rect(x, y, x+paper.Bounds().Dx(), y+paper.Bounds().Dy())
draw.Draw(img, r, paper, image.Point{}, draw.Src)
}
}
if err := wrapper.RenderLines(img, result.Lines, result.ContentStart); err != nil {
log.Fatal(err)
}
saveDocImage("richtext_comprehensive.png", img)
Output: Generated doc/richtext_comprehensive.png
Index ¶
- Constants
- Variables
- func Align(a BaselineAlignment, args ...interface{}) interface{}
- func BackgroundColor(c color.Color, args ...interface{}) interface{}
- func BgColor(c color.Color, args ...interface{}) interface{}
- func BgImage(i image.Image, args ...interface{}) interface{}
- func BgPosition(p BackgroundPositioning) interface{}
- func Border(rect fixed.Rectangle26_6, args ...interface{}) interface{}
- func BoxPadding(rect fixed.Rectangle26_6, args ...interface{}) interface{}
- func Color(c color.Color, args ...interface{}) interface{}
- func Container(args ...interface{}) interface{}
- func DPI(dpi float64) func(float64) int
- func DrawBox(i draw.Image, s image.Rectangle, dc *DrawConfig)
- func FixedBackground(args ...interface{}) interface{}
- func Highlight(c color.Color, args ...interface{}) interface{}
- func ID(id interface{}, args ...interface{}) interface{}
- func IsCR(r rune) bool
- func IsLF(r rune) bool
- func IsSpaceButNotCRLF(r rune) bool
- func Margin(rect fixed.Rectangle26_6, args ...interface{}) interface{}
- func MinWidth(w int) interface{}
- func Once(f func(r rune) bool) func(rune) bool
- func ProcessRichArgs(args ...interface{}) ([]*Content, *font.Drawer, []WrapperOption, []BoxerOption, Boxer, Tokenizer)
- func Px(v int) int
- func Reset() interface{}
- func SimpleBoxerGrab(text []rune) (int, []rune, int)
- func SimpleWrapTextToImage(text string, i Image, grf font.Face, opts ...WrapperOption) error
- func SimpleWrapTextToRect(text string, r image.Rectangle, grf font.Face, opts ...WrapperOption) (*SimpleWrapper, []Line, image.Point, error)
- func StarTokenizer(text []rune) (int, []rune, int)
- func TextColor(c color.Color, args ...interface{}) interface{}
- func TextImage(i image.Image, args ...interface{}) interface{}
- func Tiled(img image.Image) image.Image
- type AlignedBox
- type BackgroundBox
- type BackgroundImage
- type BackgroundPositioning
- type BackgroundPositioningOption
- type BaselineAlignment
- type BaselineAlignmentOption
- type BorderGroup
- type BorderOption
- type Box
- type BoxDrawMap
- type BoxEffect
- type BoxPositionStats
- type BoxRecorder
- type Boxer
- type BoxerOption
- type ContainerGroup
- type Content
- type ContentOption
- func WithAlignment(a BaselineAlignment) ContentOption
- func WithBackendImage(i image.Image) ContentOption
- func WithBackgroundColor(col color.Color) ContentOption
- func WithBoxEffects(e []BoxEffect) ContentOption
- func WithDecorators(ds ...func(Box) Box) ContentOption
- func WithFixedBackground(fixed bool) ContentOption
- func WithFont(font font.Face) ContentOption
- func WithFontColor(col color.Color) ContentOption
- func WithFontImage(i image.Image) ContentOption
- func WithID(id interface{}) ContentOption
- func WithImageScale(s float64) ContentOption
- func WithMargin(m fixed.Rectangle26_6) ContentOption
- func WithMinSize(size fixed.Point26_6) ContentOption
- func WithPadding(p fixed.Rectangle26_6) ContentOption
- type DecorationBox
- type DrawConfig
- type DrawOption
- type EffectBox
- type EffectType
- type FitterConfig
- type FitterIgnoreY
- type FitterOption
- type FixedBackgroundOption
- type Folder
- type FolderOption
- type FontColor
- type FontDrawer
- type FontImage
- type Group
- type HeightOption
- type HorizontalBlockPosition
- type HorizontalLinePosition
- type HorizontalLinePositioner
- type IDBox
- type IDOption
- type Identifier
- type Image
- type ImageBox
- func (ib *ImageBox) AdvanceRect() fixed.Int26_6
- func (ib *ImageBox) CalculateMetrics()
- func (ib *ImageBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
- func (ib *ImageBox) FontDrawer() *font.Drawer
- func (ib *ImageBox) Len() int
- func (ib *ImageBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
- func (ib *ImageBox) MetricsRect() font.Metrics
- func (ib *ImageBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
- func (ib *ImageBox) TextValue() string
- func (ib *ImageBox) Whitespace() bool
- type ImageBoxOption
- type ImageContent
- type LayoutResult
- type Line
- type LineBreakBox
- type LinePositionStats
- type MarginOption
- type MinSizeBox
- func (msb *MinSizeBox) AdvanceRect() fixed.Int26_6
- func (msb *MinSizeBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
- func (msb *MinSizeBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
- func (msb *MinSizeBox) MetricsRect() font.Metrics
- func (msb *MinSizeBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
- type MinSizeOption
- type OverflowMode
- type PaddingOption
- type PageBackgroundOption
- type PageBreakBox
- func (p *PageBreakBox) AdvanceRect() fixed.Int26_6
- func (p *PageBreakBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
- func (p *PageBreakBox) FontDrawer() *font.Drawer
- func (p *PageBreakBox) Len() int
- func (p *PageBreakBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
- func (p *PageBreakBox) MetricsRect() font.Metrics
- func (p *PageBreakBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
- func (p *PageBreakBox) TextValue() string
- func (p *PageBreakBox) Whitespace() bool
- type PageMarginOption
- type ResetOption
- type RichBoxer
- type RowBox
- func (rb *RowBox) AdvanceRect() fixed.Int26_6
- func (rb *RowBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
- func (rb *RowBox) FontDrawer() *font.Drawer
- func (rb *RowBox) Len() int
- func (rb *RowBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
- func (rb *RowBox) MetricsRect() font.Metrics
- func (rb *RowBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
- func (rb *RowBox) TextValue() string
- func (rb *RowBox) Whitespace() bool
- type SimpleBoxer
- func (sb *SimpleBoxer) Back(i int)
- func (sb *SimpleBoxer) FontDrawer() *font.Drawer
- func (sb *SimpleBoxer) HasNext() bool
- func (sb *SimpleBoxer) Next() (Box, int, error)
- func (sb *SimpleBoxer) Pos() int
- func (sb *SimpleBoxer) Push(box ...Box)
- func (sb *SimpleBoxer) Reset()
- func (sb *SimpleBoxer) SetFontDrawer(face *font.Drawer)
- func (sb *SimpleBoxer) Shift() Box
- func (sb *SimpleBoxer) Unshift(box ...Box)
- type SimpleFolder
- type SimpleLine
- func (l *SimpleLine) Boxes() []Box
- func (l *SimpleLine) DrawLine(i Image, options ...DrawOption) error
- func (l *SimpleLine) Pop() Box
- func (l *SimpleLine) PopSpaceFor(sf *SimpleFolder, r image.Rectangle, box Box) (int, error)
- func (l *SimpleLine) Push(b Box, a fixed.Int26_6)
- func (l *SimpleLine) Size() image.Rectangle
- func (l *SimpleLine) TextValue() string
- func (l *SimpleLine) YValue() int
- type SimpleTextBox
- func (sb *SimpleTextBox) AdvanceRect() fixed.Int26_6
- func (sb *SimpleTextBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
- func (sb *SimpleTextBox) FontDrawer() *font.Drawer
- func (sb *SimpleTextBox) Len() int
- func (sb *SimpleTextBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
- func (sb *SimpleTextBox) MetricsRect() font.Metrics
- func (sb *SimpleTextBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
- func (sb *SimpleTextBox) TextValue() string
- func (sb *SimpleTextBox) Whitespace() bool
- type SimpleWrapper
- func (sw *SimpleWrapper) ApplyOptions(opts ...WrapperOption)
- func (sw *SimpleWrapper) HasNext() bool
- func (sw *SimpleWrapper) RenderLines(i Image, ls []Line, at image.Point, options ...DrawOption) error
- func (sw *SimpleWrapper) TextToRect(r image.Rectangle, ops ...FitterOption) ([]Line, image.Point, error)
- func (sw *SimpleWrapper) TextToSpecs(opts ...SpecOption) (*LayoutResult, error)
- type SizeFunction
- type SourceImageMapper
- type SpecConfig
- type SpecMargin
- type SpecOption
- type Style
- type TiledImage
- type Tokenizer
- type VerticalBlockPosition
- type WidthOption
- type WrapperOption
Examples ¶
Constants ¶
const ( RSimpleBox = iota RCRLF RNIL )
Matches objects
Variables ¶
var BoxBox = boxerOptionFunc(func(f interface{}) { bf := func(box Box) { switch box := box.(type) { case interface{ turnOnBox() }: box.turnOnBox() } } switch f := f.(type) { case *SimpleBoxer: f.postBoxOptions = append(f.postBoxOptions, bf) case Box: bf(f) } })
BoxBox is a BoxerOption that tells the Box to draw a box around itself mostly for debugging purposes but will be the basis of how select and highlighting could work, such as the cursor
var BoxLine = folderOptionFunc(func(f interface{}) { if f, ok := f.(*SimpleFolder); ok { f.lineOptions = append(f.lineOptions, func(line Line) { switch line := line.(type) { case interface{ turnOnBox() }: line.turnOnBox() default: log.Printf("can't apply") } }) } })
BoxLine is a FolderOption that tells the Liner to draw a box around the line mostly for debugging purposes but will be the basis of how select and highlighting could work
var ImageBoxMetricAboveTheLine imageBoxOptionMetricCalcFunc = func(ib *ImageBox) font.Metrics { return font.Metrics{ Height: fixed.I(ib.I.Bounds().Dy()), Ascent: fixed.I(ib.I.Bounds().Dy()), } }
ImageBoxMetricAboveTheLine Puts the image above the baseline as you would expect if you were using a word processor
var ImageBoxMetricBelowTheLine imageBoxOptionMetricCalcFunc = func(ib *ImageBox) font.Metrics { return font.Metrics{ Height: fixed.I(ib.I.Bounds().Dy()), Ascent: fixed.I(ib.I.Bounds().Dy()) / 2, Descent: fixed.I(ib.I.Bounds().Dy()) - fixed.I(ib.I.Bounds().Dy())/2, } }
ImageBoxMetricBelowTheLine Puts the image above the baseline. Rarely done
var ImageBoxMetricCenter = func(fd *font.Drawer) imageBoxOptionMetricCalcFunc { return func(ib *ImageBox) font.Metrics { if fd == nil { fd = ib.fontDrawer } if fd == nil { return ImageBoxMetricBelowTheLine(ib) } m := fd.Face.Metrics() return font.Metrics{ Height: fixed.I(ib.I.Bounds().Dy()), Descent: fixed.I(ib.I.Bounds().Dy())/2 - m.Descent/2, Ascent: fixed.I(ib.I.Bounds().Dy())/2 + m.Descent/2, } } }
ImageBoxMetricCenter Puts the image running from the top down
var LatinTokenizer = SimpleBoxerGrab
LatinTokenizer is the default tokenizer for latin languages
Functions ¶
func Align ¶ added in v0.0.4
func Align(a BaselineAlignment, args ...interface{}) interface{}
Align returns a Group with BaselineAlignmentOption applied
func BackgroundColor ¶ added in v0.0.4
BackgroundColor returns a Group with BackgroundColor applied, or the Option if no args
func BgColor ¶ added in v0.0.4
BgColor returns a Group with BackgroundColor applied, or the Option if no args
func BgImage ¶ added in v0.0.4
BgImage returns a Group with BackgroundImage applied, or the Option if no args
func BgPosition ¶ added in v0.0.4
func BgPosition(p BackgroundPositioning) interface{}
BgPosition returns a BackgroundPositioningOption
func Border ¶ added in v0.0.4
func Border(rect fixed.Rectangle26_6, args ...interface{}) interface{}
Border returns a BorderGroup with Border applied
func BoxPadding ¶ added in v0.0.4
func BoxPadding(rect fixed.Rectangle26_6, args ...interface{}) interface{}
BoxPadding returns a Group with Padding applied, or the Option if no args
func Container ¶ added in v0.0.4
func Container(args ...interface{}) interface{}
Container returns a ContainerGroup.
func DrawBox ¶
func DrawBox(i draw.Image, s image.Rectangle, dc *DrawConfig)
DrawBox literally draws a simple box
func FixedBackground ¶ added in v0.0.4
func FixedBackground(args ...interface{}) interface{}
FixedBackground returns a Group with FixedBackground applied, or the Option if no args
func Highlight ¶ added in v0.0.4
Highlight returns a Group with BackgroundColor applied (Alias for BgColor)
func ID ¶ added in v0.0.4
func ID(id interface{}, args ...interface{}) interface{}
ID returns a Group with ID applied, or the Option if no args
func IsSpaceButNotCRLF ¶
IsSpaceButNotCRLF Because spaces are different to CR and LF for word wrapping
func Margin ¶ added in v0.0.4
func Margin(rect fixed.Rectangle26_6, args ...interface{}) interface{}
Margin returns a Group with Margin applied, or the Option if no args
func ProcessRichArgs ¶ added in v0.0.4
func ProcessRichArgs(args ...interface{}) ([]*Content, *font.Drawer, []WrapperOption, []BoxerOption, Boxer, Tokenizer)
ProcessRichArgs parses variadic arguments into standard components
func Reset ¶ added in v0.0.4
func Reset() interface{}
Reset returns a ResetOption to revert to plain style.
func SimpleBoxerGrab ¶
SimpleBoxerGrab Consumer of characters until change. Could be made to conform to strings.Scanner
func SimpleWrapTextToImage ¶
SimpleWrapTextToImage all in one helper function to wrap text onto an image. Use image.Image's SubImage() to specify the exact location to render:
SimpleWrapTextToImage("text", i.SubImage(image.Rect(30,30,400,400)), font)
func SimpleWrapTextToRect ¶
func SimpleWrapTextToRect(text string, r image.Rectangle, grf font.Face, opts ...WrapperOption) (*SimpleWrapper, []Line, image.Point, error)
SimpleWrapTextToRect calculates and returns the position of each box and the image.Point it would end.
func StarTokenizer ¶ added in v0.0.4
StarTokenizer is a demo tokenizer that splits on stars
func TextColor ¶ added in v0.0.4
TextColor returns a Group with FontColor applied, or the Option if no args
Types ¶
type AlignedBox ¶ added in v0.0.4
type AlignedBox struct {
Box
Alignment BaselineAlignment
}
AlignedBox wraps a box with alignment information
func (*AlignedBox) DrawBox ¶ added in v0.0.4
func (ab *AlignedBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
type BackgroundBox ¶ added in v0.0.4
type BackgroundBox struct {
Box
Background image.Image
BgPositioning BackgroundPositioning
// contains filtered or unexported fields
}
BackgroundBox is a box that has a background
func (*BackgroundBox) DrawBox ¶ added in v0.0.4
func (bb *BackgroundBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
type BackgroundImage ¶ added in v0.0.4
type BackgroundImage struct {
image.Image
Positioning *BackgroundPositioning
Fixed *bool
}
BackgroundImage defines the background
type BackgroundPositioning ¶ added in v0.0.4
type BackgroundPositioning int
BackgroundPositioning defines how the background is positioned
const ( BgPositioningSection5Zeroed BackgroundPositioning = iota // Aligned to content (inner) box 0,0 BgPositioningZeroed // Aligned to box 0,0 (Frame) BgPositioningPassThrough // Absolute Coordinates (matches dst) )
type BackgroundPositioningOption ¶ added in v0.0.4
type BackgroundPositioningOption BackgroundPositioning
type BaselineAlignment ¶ added in v0.0.4
type BaselineAlignment int
BaselineAlignment defines how content is aligned relative to the baseline.
const ( AlignBaseline BaselineAlignment = iota AlignTop AlignMiddle AlignBottom )
type BaselineAlignmentOption ¶ added in v0.0.4
type BaselineAlignmentOption BaselineAlignment
BaselineAlignmentOption wraps a BaselineAlignment.
func Alignment ¶ added in v0.0.4
func Alignment(a BaselineAlignment) BaselineAlignmentOption
Alignment returns a BaselineAlignmentOption.
type BorderOption ¶ added in v0.0.4
type BorderOption fixed.Rectangle26_6
type Box ¶
type Box interface {
// AdvanceRect returns the width of the content.
AdvanceRect() fixed.Int26_6
// MetricsRect returns the font metrics of the content.
MetricsRect() font.Metrics
// Whitespace returns true if the content is whitespace.
Whitespace() bool
// DrawBox renders the content into the given image at the specified Y offset.
DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
// FontDrawer returns the font face used for this box.
FontDrawer() *font.Drawer
// Len returns the length of the content (e.g. rune count).
Len() int
// TextValue returns the text string content of the box.
TextValue() string
// MinSize returns the minimum required size for the box (width, height).
MinSize() (fixed.Int26_6, fixed.Int26_6)
// MaxSize returns the maximum allowed size for the box (width, height).
MaxSize() (fixed.Int26_6, fixed.Int26_6)
}
Box represents a non-divisible unit of content (e.g., a word or image), which can be nested.
type BoxDrawMap ¶
type BoxDrawMap func(box Box, drawOps *DrawConfig, bps *BoxPositionStats) Box
BoxDrawMap allows the modification of boxes
func (BoxDrawMap) Apply ¶
func (s BoxDrawMap) Apply(config *DrawConfig)
Apply installs the image source mapper
type BoxEffect ¶ added in v0.0.4
type BoxEffect struct {
Func func(Image, Box, *DrawConfig)
Type EffectType
}
BoxEffect defines a graphical effect applied to a box
func Strikethrough ¶ added in v0.0.4
Strikethrough returns a Post effect
type BoxPositionStats ¶
type BoxPositionStats struct {
*LinePositionStats
NumberInLine int
PageBoxOffset int
WordOffset int
}
BoxPositionStats Box position stats
type BoxRecorder ¶ added in v0.0.4
type BoxRecorder func(box Box, min, max image.Point, bps *BoxPositionStats)
BoxRecorder allows recording of the box's position
func (BoxRecorder) Apply ¶ added in v0.0.4
func (s BoxRecorder) Apply(config *DrawConfig)
Apply installs the image source mapper
type Boxer ¶
type Boxer interface {
// Next returns the next Box.
Next() (Box, int, error)
// SetFontDrawer sets the default font for the boxer.
SetFontDrawer(face *font.Drawer)
// FontDrawer returns the default font drawer.
FontDrawer() *font.Drawer
// Back unreads the last i atoms/boxes.
Back(i int)
// HasNext returns true if there is more content to process.
HasNext() bool
// Push returns boxes to the front of the queue (stack behavior).
Push(box ...Box)
// Pos returns the current cursor position in the input.
Pos() int
// Unshift adds boxes to the beginning of the internal buffer.
Unshift(b ...Box)
// Shift removes and returns the first Box from the internal buffer.
Shift() Box
// Reset restarts the tokenization
Reset()
}
Boxer splits a line of text (or other content) into indivisible Box components.
type BoxerOption ¶
type BoxerOption interface {
// WrapperOption Allows you to pass the option to a Wrapper and assume it gets passed to the constructor of the
// Boxer
WrapperOption
// ApplyBoxConfig applies the config.
ApplyBoxConfig(interface{})
}
BoxerOption for folders
type ContainerGroup ¶ added in v0.0.4
type ContainerGroup struct {
Options []interface{}
Args []interface{}
}
ContainerGroup represents a group rendered as a separate container box.
type Content ¶ added in v0.0.4
type Content struct {
// contains filtered or unexported fields
}
Content represents a piece of text or an image with associated styling.
func NewContainerContent ¶ added in v0.0.4
func NewContainerContent(children []*Content, opts ...ContentOption) *Content
NewContainerContent creates a new container Content object.
func NewContent ¶ added in v0.0.4
func NewContent(text string, opts ...ContentOption) *Content
NewContent creates a new Content object with the given text and options.
func NewImageContent ¶ added in v0.0.4
func NewImageContent(i image.Image, opts ...ContentOption) *Content
NewImageContent creates a new Content object with the given image and options.
type ContentOption ¶ added in v0.0.4
type ContentOption func(*Content)
ContentOption is a function that can be used to configure a Content object.
func WithAlignment ¶ added in v0.0.4
func WithAlignment(a BaselineAlignment) ContentOption
WithAlignment sets the vertical alignment of a Content object.
func WithBackendImage ¶ added in v0.0.4
func WithBackendImage(i image.Image) ContentOption
WithBackendImage sets the background image of a Content object.
func WithBackgroundColor ¶ added in v0.0.4
func WithBackgroundColor(col color.Color) ContentOption
WithBackgroundColor sets the background color of a Content object.
func WithBoxEffects ¶ added in v0.0.4
func WithBoxEffects(e []BoxEffect) ContentOption
WithBoxEffects sets the effects
func WithDecorators ¶ added in v0.0.4
func WithDecorators(ds ...func(Box) Box) ContentOption
WithDecorators adds decorators to the content
func WithFixedBackground ¶ added in v0.0.4
func WithFixedBackground(fixed bool) ContentOption
WithFixedBackground sets whether the background is "fixed" (global coordinates)
func WithFont ¶ added in v0.0.4
func WithFont(font font.Face) ContentOption
WithFont sets the font of a Content object.
func WithFontColor ¶ added in v0.0.4
func WithFontColor(col color.Color) ContentOption
WithFontColor sets the font color of a Content object.
func WithFontImage ¶ added in v0.0.4
func WithFontImage(i image.Image) ContentOption
WithFontImage sets the font image of a Content object.
func WithID ¶ added in v0.0.4
func WithID(id interface{}) ContentOption
WithID sets the ID of a Content object.
func WithImageScale ¶ added in v0.0.4
func WithImageScale(s float64) ContentOption
WithImageScale sets the scale of an image Content object.
func WithMargin ¶ added in v0.0.4
func WithMargin(m fixed.Rectangle26_6) ContentOption
WithMargin sets the margin of a Content object.
func WithMinSize ¶ added in v0.0.4
func WithMinSize(size fixed.Point26_6) ContentOption
WithMinSize sets the minimum size of the content
func WithPadding ¶ added in v0.0.4
func WithPadding(p fixed.Rectangle26_6) ContentOption
WithPadding sets the padding of a Content object.
type DecorationBox ¶ added in v0.0.4
type DecorationBox struct {
Box
Padding fixed.Rectangle26_6
Margin fixed.Rectangle26_6
Background image.Image
BgPositioning BackgroundPositioning
}
DecorationBox is a box that adds padding and margin around another box
func NewDecorationBox ¶ added in v0.0.4
func NewDecorationBox(b Box, padding, margin fixed.Rectangle26_6, bg image.Image, bgPos BackgroundPositioning) *DecorationBox
NewDecorationBox constructor
func (*DecorationBox) DrawBox ¶ added in v0.0.4
func (db *DecorationBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
DrawBox renders the box with decorations.
type DrawConfig ¶
type DrawConfig struct {
SourceImageMapper SourceImageMapper
BoxDrawMap BoxDrawMap
BoxRecorder BoxRecorder
}
DrawConfig options for the drawer
func NewDrawConfig ¶
func NewDrawConfig(options ...DrawOption) *DrawConfig
NewDrawConfig construct a draw config from DrawOptions
func (*DrawConfig) ApplyMap ¶
func (c *DrawConfig) ApplyMap(b Box, bps *BoxPositionStats) Box
ApplyMap applies the box mapping function used for conditionally rendering or modifying the object being rendered
type DrawOption ¶
type DrawOption interface {
Apply(*DrawConfig)
}
DrawOption options applied and passed down the drawing functions
type EffectBox ¶ added in v0.0.4
EffectBox wraps a box with effects
func (*EffectBox) DrawBox ¶ added in v0.0.4
func (eb *EffectBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
type EffectType ¶ added in v0.0.4
type EffectType int
EffectType defines when the effect is applied
const ( EffectPre EffectType = iota EffectPost )
type FitterConfig ¶
type FitterConfig struct {
IgnoreY bool
}
type FitterIgnoreY ¶
type FitterIgnoreY struct{}
func (FitterIgnoreY) Apply ¶
func (fiy FitterIgnoreY) Apply(c *FitterConfig)
type FitterOption ¶
type FitterOption interface {
Apply(*FitterConfig)
}
type FixedBackgroundOption ¶ added in v0.0.4
type FixedBackgroundOption bool
type FolderOption ¶
type FolderOption interface {
// WrapperOption Allows you to pass the option to a Wrapper and assume it gets passed to the constructor of the
// Folder
WrapperOption
// ApplyFoldConfig applies the config.
ApplyFoldConfig(interface{})
}
FolderOption for folders
type FontDrawer ¶
type FontDrawer struct {
// contains filtered or unexported fields
}
FontDrawer a wrapper around *font.Draw used to set the font
func NewFontDrawer ¶
func NewFontDrawer(d *font.Drawer) *FontDrawer
NewFontDrawer a wrapper around *font.Draw used to set the font mostly for image
type Group ¶ added in v0.0.4
type Group struct {
Args []interface{}
}
Group collects arguments to be processed together.
type HeightOption ¶ added in v0.0.4
type HeightOption SizeFunction
HeightOption configures the height constraint
func Height ¶ added in v0.0.4
func Height(f SizeFunction) HeightOption
Height sets the height constraint
func (HeightOption) ApplySpec ¶ added in v0.0.4
func (f HeightOption) ApplySpec(c *SpecConfig)
type HorizontalBlockPosition ¶
type HorizontalBlockPosition int
HorizontalBlockPosition information about how to position the entire block of text rather than just the line horizontally
const ( // LeftBLock positions the entire block of text left rather than just the line horizontally (default) LeftBLock HorizontalBlockPosition = iota // HorizontalCenterBlock positions the entire block of text center rather than just the line horizontally HorizontalCenterBlock // RightBlock positions the entire block of text right rather than just the line horizontally RightBlock )
func (HorizontalBlockPosition) ApplyWrapperConfig ¶
func (hp HorizontalBlockPosition) ApplyWrapperConfig(wr interface{})
ApplyWrapperConfig Stores the position against the wrapper object
type HorizontalLinePosition ¶
type HorizontalLinePosition int
HorizontalLinePosition is the type for per-line level alignment.
const ( // LeftLines default, produces lines that are individually left justified. LeftLines HorizontalLinePosition = iota // HorizontalCenterLines produces lines that are individually center justified. HorizontalCenterLines // RightLines produces lines that are individually right justified. RightLines )
func (HorizontalLinePosition) ApplyFoldConfig ¶
func (hp HorizontalLinePosition) ApplyFoldConfig(f interface{})
ApplyFoldConfig applies the configuration to the wrapper where it will be stored in the line.
func (HorizontalLinePosition) ApplyWrapperConfig ¶
func (hp HorizontalLinePosition) ApplyWrapperConfig(wr interface{})
ApplyWrapperConfig Is required to pass the configuration through to the appropriate level -- Hopefully will be refactored
type HorizontalLinePositioner ¶
type HorizontalLinePositioner interface {
// contains filtered or unexported methods
}
HorizontalLinePositioner is a simple interface denoting a getter
type IDBox ¶ added in v0.0.4
type IDBox struct {
Box
// contains filtered or unexported fields
}
IDBox wrapper for box with ID
type Identifier ¶ added in v0.0.4
type Identifier interface {
ID() interface{}
}
Identifier is a interface for reporting IDs
type ImageBox ¶
type ImageBox struct {
I image.Image
Scale float64
M font.Metrics
// contains filtered or unexported fields
}
ImageBox is a box that contains an image
func NewImageBox ¶
func NewImageBox(i image.Image, options ...ImageBoxOption) *ImageBox
NewImageBox constructs a new ImageBox
func (*ImageBox) AdvanceRect ¶
AdvanceRect width of text
func (*ImageBox) CalculateMetrics ¶
func (ib *ImageBox) CalculateMetrics()
CalculateMetrics calculate dimension and positioning
func (*ImageBox) DrawBox ¶
func (ib *ImageBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
DrawBox renders object
func (*ImageBox) MetricsRect ¶
MetricsRect all other font details of text
func (*ImageBox) TextValue ¶
TextValue returns the text suppressed by the line break (probably a white space including a \r\n)
func (*ImageBox) Whitespace ¶
Whitespace if this is a white space or not
type ImageBoxOption ¶
type ImageBoxOption interface {
// contains filtered or unexported methods
}
ImageBoxOption modifiers for the ImageBox
type ImageContent ¶ added in v0.0.4
ImageContent represents an inline image.
type LayoutResult ¶ added in v0.0.4
type LayoutResult struct {
Lines []Line
PageSize image.Point
ContentStart image.Point
Margin SpecMargin
PageBackground color.Color
}
LayoutResult holds the result of the text layout
type Line ¶
type Line interface {
// Size the line consumes
Size() image.Rectangle
// DrawLine draws the line
DrawLine(i Image, options ...DrawOption) error
// Boxes are the lines contents
Boxes() []Box
// TextValue extracts the text value
TextValue() string
// YValue where the baseline is
YValue() int
// PopSpaceFor will push box at the end, if there isn't enough width, it will make width space.
PopSpaceFor(sf *SimpleFolder, r image.Rectangle, box Box) (int, error)
// contains filtered or unexported methods
}
Line refers to a literal line of text
type LineBreakBox ¶
type LineBreakBox struct {
// Box is the box that linebreak contains if any
Box
}
LineBreakBox represents a natural or an effective line break
func (*LineBreakBox) AdvanceRect ¶
func (sb *LineBreakBox) AdvanceRect() fixed.Int26_6
type LinePositionStats ¶
LinePositionStats numbers to use for pin pointing location
func (*LinePositionStats) BoxPositionStats ¶
func (lps *LinePositionStats) BoxPositionStats(numberInLine int) *BoxPositionStats
BoxPositionStats generates object of same name
type MarginOption ¶ added in v0.0.4
type MarginOption fixed.Rectangle26_6
type MinSizeBox ¶ added in v0.0.4
MinSizeBox ensures the box has a minimum size
func (*MinSizeBox) AdvanceRect ¶ added in v0.0.4
func (msb *MinSizeBox) AdvanceRect() fixed.Int26_6
func (*MinSizeBox) DrawBox ¶ added in v0.0.4
func (msb *MinSizeBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
func (*MinSizeBox) MaxSize ¶ added in v0.0.4
func (msb *MinSizeBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
func (*MinSizeBox) MetricsRect ¶ added in v0.0.4
func (msb *MinSizeBox) MetricsRect() font.Metrics
type MinSizeOption ¶ added in v0.0.4
type OverflowMode ¶
type OverflowMode int
OverflowMode Ways of describing overflow
const ( // StrictBorders default overflow mode. Do not allow StrictBorders OverflowMode = iota // DescentOverflow Allow some decent overflow. Characters such as yjqp will overflow DescentOverflow // FullOverflowDuplicate Will allow the full line to overflow, and duplicate line next run FullOverflowDuplicate )
type PaddingOption ¶ added in v0.0.4
type PaddingOption fixed.Rectangle26_6
type PageBackgroundOption ¶ added in v0.0.4
PageBackgroundOption sets the page background color
func PageBackground ¶ added in v0.0.4
func PageBackground(c color.Color) PageBackgroundOption
func (PageBackgroundOption) ApplySpec ¶ added in v0.0.4
func (o PageBackgroundOption) ApplySpec(c *SpecConfig)
type PageBreakBox ¶
type PageBreakBox struct {
// VisualBox is the box to render and use
VisualBox Box
// ContainerBox is the box that linebreak contains if any
ContainerBox Box
}
PageBreakBox represents a natural or an effective page break
func NewPageBreak ¶
func NewPageBreak(pbb Box) *PageBreakBox
NewPageBreak basic constructor for a page break.
func (*PageBreakBox) AdvanceRect ¶
func (p *PageBreakBox) AdvanceRect() fixed.Int26_6
AdvanceRect width of text
func (*PageBreakBox) DrawBox ¶
func (p *PageBreakBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
DrawBox renders object
func (*PageBreakBox) FontDrawer ¶
func (p *PageBreakBox) FontDrawer() *font.Drawer
FontDrawer font used
func (*PageBreakBox) Len ¶
func (p *PageBreakBox) Len() int
Len the length of the buffer represented by the box
func (*PageBreakBox) MaxSize ¶ added in v0.0.4
func (p *PageBreakBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
func (*PageBreakBox) MetricsRect ¶
func (p *PageBreakBox) MetricsRect() font.Metrics
MetricsRect all other font details of text
func (*PageBreakBox) MinSize ¶ added in v0.0.4
func (p *PageBreakBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
func (*PageBreakBox) TextValue ¶
func (p *PageBreakBox) TextValue() string
TextValue returns the text suppressed by the line break (probably a white space including a \r\n)
func (*PageBreakBox) Whitespace ¶
func (p *PageBreakBox) Whitespace() bool
Whitespace if contains a white space or not
type PageMarginOption ¶ added in v0.0.4
PageMargin sets the margin option
func Padding ¶ added in v0.0.4
func Padding(margin int, c color.Color) PageMarginOption
Padding sets the margin option (Alias for PageMargin)
func (PageMarginOption) ApplySpec ¶ added in v0.0.4
func (o PageMarginOption) ApplySpec(c *SpecConfig)
type ResetOption ¶ added in v0.0.4
type ResetOption struct{}
type RichBoxer ¶ added in v0.0.4
type RichBoxer = SimpleBoxer
RichBoxer alias for backward compatibility
type RowBox ¶ added in v0.0.4
type RowBox struct {
Boxes []Box
}
RowBox holds multiple boxes on a single line
func (*RowBox) AdvanceRect ¶ added in v0.0.4
func (*RowBox) DrawBox ¶ added in v0.0.4
func (rb *RowBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
func (*RowBox) FontDrawer ¶ added in v0.0.4
func (*RowBox) MetricsRect ¶ added in v0.0.4
func (*RowBox) Whitespace ¶ added in v0.0.4
type SimpleBoxer ¶
type SimpleBoxer struct {
Tokenizer Tokenizer
// contains filtered or unexported fields
}
SimpleBoxer simple tokenizer basically determines if something unicode.IsSpace or is a new line, or is text and tells the calling Folder that. Putting the elements in the correct Box. SimpleBoxer simple tokenizer basically determines if something unicode.IsSpace or is a new line, or is text and tells the calling Folder that. Putting the elements in the correct Box.
func NewRichBoxer ¶ added in v0.0.4
func NewRichBoxer(args ...interface{}) *SimpleBoxer
NewRichBoxer creates a new boxer using a variety of arguments to create the contents and options
func NewSimpleBoxer ¶
func NewSimpleBoxer(contents []*Content, drawer *font.Drawer, options ...BoxerOption) *SimpleBoxer
NewSimpleBoxer simple tokenizer basically determines if something unicode.IsSpace or is a new line, or is text and tells the calling Folder that. Putting the elements in the correct Box.
func (*SimpleBoxer) FontDrawer ¶
func (sb *SimpleBoxer) FontDrawer() *font.Drawer
FontDrawer encapsulates default fonts and more
func (*SimpleBoxer) Next ¶
func (sb *SimpleBoxer) Next() (Box, int, error)
Next gets the next word in a Box
func (*SimpleBoxer) Push ¶
func (sb *SimpleBoxer) Push(box ...Box)
Push puts a box back on to the cache stack
func (*SimpleBoxer) Reset ¶ added in v0.0.4
func (sb *SimpleBoxer) Reset()
Reset restarts the tokenization
func (*SimpleBoxer) SetFontDrawer ¶
func (sb *SimpleBoxer) SetFontDrawer(face *font.Drawer)
SetFontDrawer Changes the default font
func (*SimpleBoxer) Shift ¶
func (sb *SimpleBoxer) Shift() Box
func (*SimpleBoxer) Unshift ¶
func (sb *SimpleBoxer) Unshift(box ...Box)
Unshift basically is Push but to the start
type SimpleFolder ¶
type SimpleFolder struct {
// contains filtered or unexported fields
}
SimpleFolder is a simple Folder
func NewSimpleFolder ¶
func NewSimpleFolder(boxer Boxer, container image.Rectangle, lastFontDrawer *font.Drawer, options ...FolderOption) *SimpleFolder
NewSimpleFolder constructs a SimpleFolder applies options provided.
func (*SimpleFolder) NewLine ¶
func (sf *SimpleFolder) NewLine() *SimpleLine
NewLine constructs a new simple line. (Later to be a factory proxy)
type SimpleLine ¶
type SimpleLine struct {
// contains filtered or unexported fields
}
SimpleLine is a simple implementation to prevent name space names later. Represents a line
func (*SimpleLine) DrawLine ¶
func (l *SimpleLine) DrawLine(i Image, options ...DrawOption) error
DrawLine renders image to image, you can control the location by using the SubImage function.
func (*SimpleLine) Pop ¶
func (l *SimpleLine) Pop() Box
Pop a box off of the end of a line. Ignores all height components that will require a recalculation, drops PageBreak
func (*SimpleLine) PopSpaceFor ¶
func (l *SimpleLine) PopSpaceFor(sf *SimpleFolder, r image.Rectangle, box Box) (int, error)
PopSpaceFor will push box at the end, if there isn't enough width, it will make width space.
func (*SimpleLine) Push ¶
func (l *SimpleLine) Push(b Box, a fixed.Int26_6)
Push a box onto the end, and also copy values in appropriately
func (*SimpleLine) Size ¶
func (l *SimpleLine) Size() image.Rectangle
Size is the size consumed of the line
func (*SimpleLine) TextValue ¶
func (l *SimpleLine) TextValue() string
TextValue extracts the text value of the line
type SimpleTextBox ¶
type SimpleTextBox struct {
Contents string
Bounds fixed.Rectangle26_6
Advance fixed.Int26_6
Metrics font.Metrics
// contains filtered or unexported fields
}
SimpleTextBox represents an indivisible series of characters.
func (*SimpleTextBox) AdvanceRect ¶
func (sb *SimpleTextBox) AdvanceRect() fixed.Int26_6
AdvanceRect width of text
func (*SimpleTextBox) DrawBox ¶
func (sb *SimpleTextBox) DrawBox(i Image, y fixed.Int26_6, dc *DrawConfig)
DrawBox renders object
func (*SimpleTextBox) FontDrawer ¶
func (sb *SimpleTextBox) FontDrawer() *font.Drawer
FontDrawer font used
func (*SimpleTextBox) Len ¶
func (sb *SimpleTextBox) Len() int
Len is the string length of the contents of the box
func (*SimpleTextBox) MaxSize ¶ added in v0.0.4
func (sb *SimpleTextBox) MaxSize() (fixed.Int26_6, fixed.Int26_6)
func (*SimpleTextBox) MetricsRect ¶
func (sb *SimpleTextBox) MetricsRect() font.Metrics
MetricsRect all other font details of text
func (*SimpleTextBox) MinSize ¶ added in v0.0.4
func (sb *SimpleTextBox) MinSize() (fixed.Int26_6, fixed.Int26_6)
func (*SimpleTextBox) TextValue ¶
func (sb *SimpleTextBox) TextValue() string
TextValue stored value of the box
func (*SimpleTextBox) Whitespace ¶
func (sb *SimpleTextBox) Whitespace() bool
Whitespace if this is a white space or not
type SimpleWrapper ¶
type SimpleWrapper struct {
// contains filtered or unexported fields
}
SimpleWrapper provides basic text wrapping functionality.
func NewRichWrapper ¶ added in v0.0.4
func NewRichWrapper(args ...interface{}) *SimpleWrapper
NewRichWrapper creates a new wrapper. valid args are font.Face, string, and WrapperOption
func NewSimpleWrapper ¶
func NewSimpleWrapper(contents []*Content, grf font.Face, opts ...WrapperOption) *SimpleWrapper
NewSimpleWrapper creates a new wrapper. This function retains previous text position, useful for creating "pages." assumes black text
func (*SimpleWrapper) ApplyOptions ¶
func (sw *SimpleWrapper) ApplyOptions(opts ...WrapperOption)
ApplyOptions allows the application of options to the SimpleWrapper (Such as new fonts, or turning on / off boxes.
func (*SimpleWrapper) HasNext ¶
func (sw *SimpleWrapper) HasNext() bool
HasNext are there any unprocessed bytes in the boxer
func (*SimpleWrapper) RenderLines ¶
func (sw *SimpleWrapper) RenderLines(i Image, ls []Line, at image.Point, options ...DrawOption) error
RenderLines draws the boxes for the given lines. on the image, starting at the specified point ignoring the original boundaries but maintaining the wrapping. Also applies alignment options.
func (*SimpleWrapper) TextToRect ¶
func (sw *SimpleWrapper) TextToRect(r image.Rectangle, ops ...FitterOption) ([]Line, image.Point, error)
TextToRect calculates and returns the position of each box and the image.Point it would end.
func (*SimpleWrapper) TextToSpecs ¶ added in v0.0.4
func (sw *SimpleWrapper) TextToSpecs(opts ...SpecOption) (*LayoutResult, error)
TextToSpecs performs layout based on complex constraints. It returns the layout result containing lines, page size, and offsets.
Example (A4) ¶
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
wordwrap "github.com/arran4/golang-wordwrap"
"github.com/arran4/golang-wordwrap/util"
)
// Helper to save image for documentation
func saveDocImage(name string, img image.Image) {
f, err := os.Create("doc/" + name)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal(err)
}
}()
if err := png.Encode(f, img); err != nil {
log.Fatal(err)
}
fmt.Printf("Generated doc/%s\n", name)
}
func main() {
gr, err := util.OpenFont("goregular")
if err != nil {
log.Fatal(err)
}
font := util.GetFontFace(24, 96, gr)
text := "This is an example of an A4 document layout. It uses a fixed A4 width and standard padding."
wrapper := wordwrap.NewRichWrapper(
font,
text,
)
// Layout Specs: A4 Width (96 DPI), 20px Padding, White Background
result, err := wrapper.TextToSpecs(
wordwrap.Width(wordwrap.A4Width(96)),
wordwrap.Padding(20, color.Black),
wordwrap.PageBackground(color.White),
)
if err != nil {
log.Fatal(err)
}
img := image.NewRGBA(image.Rect(0, 0, result.PageSize.X, result.PageSize.Y))
// Draw Background
if result.PageBackground != nil {
draw.Draw(img, img.Bounds(), &image.Uniform{result.PageBackground}, image.Point{}, draw.Src)
}
if err := wrapper.RenderLines(img, result.Lines, result.ContentStart); err != nil {
log.Fatal(err)
}
saveDocImage("a4_example.png", img)
}
Output: Generated doc/a4_example.png
Example (A4_full) ¶
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
wordwrap "github.com/arran4/golang-wordwrap"
"github.com/arran4/golang-wordwrap/util"
)
// Helper to save image for documentation
func saveDocImage(name string, img image.Image) {
f, err := os.Create("doc/" + name)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal(err)
}
}()
if err := png.Encode(f, img); err != nil {
log.Fatal(err)
}
fmt.Printf("Generated doc/%s\n", name)
}
func main() {
gr, err := util.OpenFont("goregular")
if err != nil {
log.Fatal(err)
}
font := util.GetFontFace(24, 96, gr)
text := "This is an example of a full A4 document layout. It uses a fixed A4 width and height."
wrapper := wordwrap.NewRichWrapper(
font,
text,
)
// Layout Specs: A4 Width & Height (96 DPI), 20px Padding, White Background
result, err := wrapper.TextToSpecs(
wordwrap.Width(wordwrap.A4Width(96)),
wordwrap.Height(wordwrap.A4Height(96)),
wordwrap.Padding(20, color.Black),
wordwrap.PageBackground(color.White),
)
if err != nil {
log.Fatal(err)
}
img := image.NewRGBA(image.Rect(0, 0, result.PageSize.X, result.PageSize.Y))
// Draw Background
if result.PageBackground != nil {
draw.Draw(img, img.Bounds(), &image.Uniform{result.PageBackground}, image.Point{}, draw.Src)
}
if err := wrapper.RenderLines(img, result.Lines, result.ContentStart); err != nil {
log.Fatal(err)
}
saveDocImage("a4_full_example.png", img)
}
Output: Generated doc/a4_full_example.png
Example (Flexible) ¶
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
wordwrap "github.com/arran4/golang-wordwrap"
"github.com/arran4/golang-wordwrap/util"
)
// Helper to save image for documentation
func saveDocImage(name string, img image.Image) {
f, err := os.Create("doc/" + name)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal(err)
}
}()
if err := png.Encode(f, img); err != nil {
log.Fatal(err)
}
fmt.Printf("Generated doc/%s\n", name)
}
func main() {
// Layout using a flexible width constraint: at most A4 width, but shrinking to content (Natural) width if smaller.
gr, err := util.OpenFont("goregular")
if err != nil {
log.Fatal(err)
}
font := util.GetFontFace(24, 96, gr)
// Long text to demonstrate wrapping
wrapper := wordwrap.NewRichWrapper(
font,
"This text will wrap at A4 width because of the constraint logic.",
)
result, err := wrapper.TextToSpecs(
wordwrap.Width(wordwrap.Min(wordwrap.A4Width(96), wordwrap.Unbounded())),
wordwrap.PageBackground(color.White),
)
if err != nil {
log.Fatal(err)
}
img := image.NewRGBA(image.Rect(0, 0, result.PageSize.X, result.PageSize.Y))
if result.PageBackground != nil {
draw.Draw(img, img.Bounds(), &image.Uniform{result.PageBackground}, image.Point{}, draw.Src)
}
if err := wrapper.RenderLines(img, result.Lines, result.ContentStart); err != nil {
log.Fatal(err)
}
saveDocImage("flexible_example.png", img)
}
Output: Generated doc/flexible_example.png
Example (Simple) ¶
package main
import (
"fmt"
"image"
"image/png"
"log"
"os"
wordwrap "github.com/arran4/golang-wordwrap"
"github.com/arran4/golang-wordwrap/util"
)
// Helper to save image for documentation
func saveDocImage(name string, img image.Image) {
f, err := os.Create("doc/" + name)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal(err)
}
}()
if err := png.Encode(f, img); err != nil {
log.Fatal(err)
}
fmt.Printf("Generated doc/%s\n", name)
}
func main() {
// Open Font
gr, err := util.OpenFont("goregular")
if err != nil {
log.Fatal(err)
}
font := util.GetFontFace(24, 96, gr)
// Standard Wrapper Args
args := []interface{}{
font,
"Simple Text wrapping example.",
}
// Create Wrapper
wrapper := wordwrap.NewRichWrapper(args...)
// Layout with Constraint: Fixed Width 200px
result, err := wrapper.TextToSpecs(wordwrap.Width(wordwrap.Fixed(200)))
if err != nil {
log.Fatal(err)
}
// Render
img := image.NewRGBA(image.Rect(0, 0, result.PageSize.X, result.PageSize.Y))
if err := wrapper.RenderLines(img, result.Lines, result.ContentStart); err != nil {
log.Fatal(err)
}
saveDocImage("simple_example.png", img)
}
Output: Generated doc/simple_example.png
type SizeFunction ¶ added in v0.0.4
SizeFunction determines a size based on the measured content size
func Auto ¶ added in v0.0.4
func Auto() SizeFunction
Auto returns the content size (identity). Same as Unbounded in this context.
func Max ¶ added in v0.0.4
func Max(a, b SizeFunction) SizeFunction
Max returns the maximum of two size functions.
func Min ¶ added in v0.0.4
func Min(a, b SizeFunction) SizeFunction
Min returns the minimum of two size functions.
type SourceImageMapper ¶
SourceImageMapper allows passing in of an option that will map the original input in some way
func (SourceImageMapper) Apply ¶
func (s SourceImageMapper) Apply(config *DrawConfig)
Apply installs the image source mapper
type SpecConfig ¶ added in v0.0.4
type SpecConfig struct {
WidthFn SizeFunction
HeightFn SizeFunction
Margin SpecMargin
PageBackground color.Color
}
SpecConfig holds configuration for TextToSpecs
type SpecMargin ¶ added in v0.0.4
type SpecOption ¶ added in v0.0.4
type SpecOption interface {
ApplySpec(config *SpecConfig)
}
SpecOption configures the TextToSpecs layout
type Style ¶ added in v0.0.4
type Style struct {
FontDrawerSrc image.Image
BackgroundColor image.Image // can be used for colour or image
Padding fixed.Rectangle26_6
Margin fixed.Rectangle26_6
Alignment BaselineAlignment
Effects []BoxEffect
FixedBackground bool
BgPositioning BackgroundPositioning
Border fixed.Rectangle26_6
BorderImage image.Image
Decorators []func(Box) Box
MinSize fixed.Point26_6
// contains filtered or unexported fields
}
Style defines the visual properties of content.
type TiledImage ¶ added in v0.0.4
TiledImage implements infinite tiling of a source image
func (*TiledImage) Bounds ¶ added in v0.0.4
func (t *TiledImage) Bounds() image.Rectangle
func (*TiledImage) ColorModel ¶ added in v0.0.4
func (t *TiledImage) ColorModel() color.Model
type VerticalBlockPosition ¶
type VerticalBlockPosition int
VerticalBlockPosition information about how to position the entire block of text rather than just the line vertically
const ( // TopBLock positions the entire block of text top TopBLock VerticalBlockPosition = iota // VerticalCenterBlock positions the entire block of text center VerticalCenterBlock // BottomBlock positions the entire block of text bottom BottomBlock )
func (VerticalBlockPosition) ApplyWrapperConfig ¶
func (hp VerticalBlockPosition) ApplyWrapperConfig(wr interface{})
ApplyWrapperConfig Stores the position against the wrapper object
type WidthOption ¶ added in v0.0.4
type WidthOption SizeFunction
WidthOption configures the width constraint
func (WidthOption) ApplySpec ¶ added in v0.0.4
func (f WidthOption) ApplySpec(c *SpecConfig)
type WrapperOption ¶
type WrapperOption interface {
// ApplyWrapperConfig applies the config.
ApplyWrapperConfig(interface{})
}
WrapperOption for folders
func NewPageBreakBox ¶
func NewPageBreakBox(b Box, opts ...BoxerOption) WrapperOption
NewPageBreakBox is a FolderOption that tells the Liner to add a chevron image to the end of every text block that continues past the given rect.
func YOverflow ¶
func YOverflow(i OverflowMode) WrapperOption
YOverflow is a FolderOption that sets the type over overflow mode we will allow
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
dogoal
command
|
|
|
generatesample
command
|
|
|
pagelimits
command
|
|
|
richwraptoimage
command
|
|
|
simplewraptoimage
command
|
|
|
texttoimage
command
|
|





















