Created
November 7, 2016 06:21
-
-
Save tommy351/1438841aa54fc33ea9eb31d2c2aa5975 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func drawLine(gc *draw2dimg.GraphicContext, str string, maxX float64, maxY float64, x float64, y float64) (bool, float64) { | |
// Handle empty line | |
if len(strings.TrimSpace(str)) == 0 { | |
return false, y + gc.Current.FontSize*lineHeight | |
} | |
list := []rune(str) | |
length := len(list) | |
offsetX := x | |
offsetY := y | |
fontSize := gc.Current.FontSize | |
lineSize := fontSize * lineHeight | |
for i := 0; i < length; i++ { | |
chunk := string(list[i]) | |
textWidth := gc.FillStringAt(chunk, offsetX, offsetY) | |
offsetX += textWidth | |
if offsetX >= maxX { | |
newY := offsetY + lineSize | |
if newY >= maxY { | |
return true, offsetY | |
} | |
offsetX = x | |
offsetY = newY | |
} | |
} | |
offsetY += lineSize | |
return false, offsetY | |
} | |
func drawText(gc *draw2dimg.GraphicContext, str string, width float64, height float64, x float64, y float64) { | |
// Trim newlines | |
str = strings.Trim(str, "\r\n") | |
// Split by lines | |
lines := strings.Split(str, "\n") | |
// Initial offset | |
offsetY := y | |
maxX := width + x | |
maxY := height + y | |
for _, line := range lines { | |
end, newY := drawLine(gc, line, maxX, maxY, x, offsetY) | |
if end || newY >= maxY { | |
break | |
} | |
offsetY = newY | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment