I spent some time thinking about how to do word-wrap for non-fixed-width fonts, and came up with this. It's pretty simple, but works well and seems fast enough for me. I thought someone else my like it, too!
Here's the wordwrap method:
def wordwrap(message,width,font)
word_array = message.split(' ')
lines = [word_array.shift]
word_array.each do |word|
if font.text_width("#{lines[-1]} #{word}") < width
lines[-1] << ' ' << word
else
lines.push(word)
end
end
return lines
end
and here's a demonstration of use:
#!/usr/local/bin/ruby
require 'gosu'
class MyWindow < Gosu::Window
def initialize
super(640,480,false)
@font = Gosu::Font.new(self,Gosu::default_font_name,20)
@message = "Hello and welcome to my very long text string which is also pretty boring and stupid, but oh well I guess there is a time and a place for lorum ipsum, and this was probably it, but I didn't have any handy so we get this crap instead, which is too bad really, because Lorem Ipsum is kinda nice, but oh well, what can you do, other than end this damn string already?"
@margin = 20
body_width = self.width - 2*@margin
@lines = wordwrap(@message,body_width,@font)
end
def wordwrap(message,width,font)
word_array = message.split(' ')
lines = [word_array.shift]
word_array.each do |word|
if font.text_width("#{lines[-1]} #{word}") < width
lines[-1] << ' ' << word
else
lines.push(word)
end
end
return lines
end
def draw
@lines.each_with_index do |line,index|
height = @margin + (index * @font.height)
@font.draw(line,@margin,height,0)
end
end
end
By jlnr (dev)
Date 2009-03-23 23:55
But your version is useful for those cases where you can't just interrupt the game's flow with the creation of an Image, something that might be costly (it currently is so on the iPhone and I'm not sure it's easy to fix) :)
I've seen the bug and hope it was really the problem that I put into the comment. That part of SWIG is really tricky and it took me a while to figure it out both times it broke :(
Loading...