Skip to content

Commit fb4b08c

Browse files
authored
Merge pull request #64 from ffreyer/fix_spacing
Fix character spacing in `renderstring!`
2 parents 4db586e + bf43e8c commit fb4b08c

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/rendering.jl

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,18 @@ function renderstring!(
5757

5858
bitmaps = Vector{Matrix{UInt8}}(undef, lastindex(str))
5959
metrics = Vector{FontExtent{Int}}(undef, lastindex(str))
60+
# ymin and ymax w.r.t the baseline
6061
ymin = ymax = sumadvancex = 0
6162

6263
for (istr, char) = enumerate(str)
6364
bitmap, metric_float = renderface(face, char, pixelsize)
6465
metric = round.(Int, metric_float)
6566
bitmaps[istr] = bitmap
6667
metrics[istr] = metric
68+
69+
# scale of glyph (size of bitmap)
6770
w, h = metric.scale
71+
# offset between glyph origin and bitmap top left corner
6872
bx, by = metric.horizontal_bearing
6973
ymin = min(ymin, by - h)
7074
ymax = max(ymax, by)
@@ -80,7 +84,7 @@ function renderstring!(
8084
bitmapmax = typemax(eltype(bitmaps[1]))
8185

8286
imgh, imgw = size(img)
83-
if bcolor != nothing
87+
if bcolor !== nothing
8488
img[
8589
clamp(py-ymax+1, 1, imgh) : clamp(py-ymin-1, 1, imgh),
8690
clamp(px-1, 1, imgw) : clamp(px+sumadvancex-1, 1, imgw)
@@ -91,27 +95,31 @@ function renderstring!(
9195
for (istr, char) = enumerate(str)
9296
w, h = metrics[istr].scale
9397
bx, by = metrics[istr].horizontal_bearing
98+
9499
if istr == 1
95100
prev_char = char
96101
else
97102
kx, ky = map(x-> round(Int, x), kerning(prev_char, char, face))
98103
px += kx
99104
end
100-
cliprowlo, cliprowhi = max(0, by-py), max(0, h+py-by-imgh)
101-
clipcollo, clipcolhi = max(0, bx-px), max(0, w+px-bx-imgw)
102-
if bcolor == nothing
105+
106+
# trim parts of glyph images that are outside the destination
107+
cliprowlo, cliprowhi = max(0, -(py-by)), max(0, py - by + h - imgh)
108+
clipcollo, clipcolhi = max(0, -bx-px), max(0, px + bx + w - imgw)
109+
110+
if bcolor === nothing
103111
for row = 1+cliprowlo : h-cliprowhi, col = 1+clipcollo : w-clipcolhi
104112
bitmaps[istr][col,row]==0 && continue
105113
c1 = bitmaps[istr][col,row] / bitmapmax * fcolor
106-
img[row+py-by, col+px-bx] = T <: Integer ? round(T, c1) : T(c1)
114+
img[row+py-by, col+px+bx] = T <: Integer ? round(T, c1) : T(c1)
107115
end
108116
else
109117
for row = 1+cliprowlo : h-cliprowhi, col = 1+clipcollo : w-clipcolhi
110118
bitmaps[istr][col, row] == 0 && continue
111119
w1 = bitmaps[istr][col, row] / bitmapmax
112120
c1 = w1 * fcolor
113121
c0 = (1.0 - w1) * bcolor
114-
img[row + py - by, col + px - bx] = T <: Integer ? round(T, c1 + c0) : T(c1 + c0)
122+
img[row + py - by, col + px + bx] = T <: Integer ? round(T, c1 + c0) : T(c1 + c0)
115123
end
116124
end
117125
px += metrics[istr].advance[1]

0 commit comments

Comments
 (0)