Skip to content

Instantly share code, notes, and snippets.

@sshirokov
Created November 22, 2014 09:08
Show Gist options
  • Select an option

  • Save sshirokov/6839643b0df7682a6e37 to your computer and use it in GitHub Desktop.

Select an option

Save sshirokov/6839643b0df7682a6e37 to your computer and use it in GitHub Desktop.
A rough sketch of text wrapping into a constrained width
textSize = (msg, font, size) ->
bb = (GD.create(1,1)).stringFTBBox(black, font, size, 0, 0, 0, msg)
[
bb[2] - bb[0],
bb[1] - bb[7]
]
chunkInputInto = (msg, splits) ->
stepSize = Math.round(msg.length / splits)
chunks = []
for n in [0...splits]
chunks[n] = msg[...stepSize]
msg = msg[stepSize..]
# Shift words down until the last space in this line and
# give them back to the buffer
while not /\s$/.test(chunks[n])
chunkLen = chunks[n].length
msg = "#{chunks[n][chunkLen - 1]}#{msg}"
chunks[n] = chunks[n][...-1]
return chunks.map (c) -> c.trim()
baloon = (msg, font="./ayp-template-images/arial.ttf", size=12, max=330) ->
msg = msg.trim()
[w, h] = textSize(msg, font, size)
console.log "BB: ", [w, h], " of '#{msg}'"
if w > max
splits = Math.round(w / max)
splits += 1 if w % max
msg = chunkInputInto(msg, splits).join "\n"
else
msg
@SolientArt

Copy link
Copy Markdown

Doctor! My brain hurts!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment