···
149
149
baselineAnchor := layer.Anchor == "baseline"
150
150
metrics := face.Metrics()
151
151
152
152
-
if layer.WrapWidth > 0 {
153
153
-
dc.DrawStringWrapped(txt, x, y, ax, ay, layer.WrapWidth, 1.5, gg.AlignLeft)
154
154
-
return nil
152
152
+
var lines []string
153
153
+
for _, segment := range strings.Split(txt, "\n") {
154
154
+
if layer.WrapWidth > 0 {
155
155
+
lines = append(lines, wrapText(face, segment, layer.WrapWidth, layer.Spacing)...)
156
156
+
} else {
157
157
+
lines = append(lines, segment)
158
158
+
}
155
159
}
156
160
157
157
-
lines := strings.Split(txt, "\n")
158
161
lineH := layer.Size * 1.2
159
162
totalH := float64(len(lines)-1) * lineH
160
163
for i, line := range lines {
···
168
171
baselineY = lineY + metrics.Ascent - ay*boxH
169
172
}
170
173
171
171
-
n := utf8.RuneCountInString(line)
172
172
-
totalW := face.Advance(line)
173
173
-
if n > 1 {
174
174
-
totalW += layer.Spacing * float64(n-1)
175
175
-
}
174
174
+
totalW := measureLine(face, line, layer.Spacing)
176
175
drawLine(dc, face, line, x-ax*totalW, baselineY, layer.Spacing)
177
176
}
178
177
return nil
···
220
219
221
220
dc.DrawImageEx(img, gg.DrawImageOptions{X: imgX, Y: imgY, DstWidth: dstW, DstHeight: dstH, Opacity: opacity})
222
221
return nil
222
222
+
}
223
223
+
224
224
+
func measureLine(face text.Face, s string, spacing float64) float64 {
225
225
+
n := utf8.RuneCountInString(s)
226
226
+
w := face.Advance(s)
227
227
+
if n > 1 {
228
228
+
w += spacing * float64(n-1)
229
229
+
}
230
230
+
return w
231
231
+
}
232
232
+
233
233
+
func wrapText(face text.Face, s string, maxWidth, spacing float64) []string {
234
234
+
words := strings.Fields(s)
235
235
+
if len(words) == 0 {
236
236
+
return []string{""}
237
237
+
}
238
238
+
var lines []string
239
239
+
current := words[0]
240
240
+
for _, word := range words[1:] {
241
241
+
candidate := current + " " + word
242
242
+
if measureLine(face, candidate, spacing) > maxWidth {
243
243
+
lines = append(lines, current)
244
244
+
current = word
245
245
+
} else {
246
246
+
current = candidate
247
247
+
}
248
248
+
}
249
249
+
return append(lines, current)
223
250
}
224
251
225
252
// drawLine draws a single pre-positioned line at the given baseline.