1

Im trying to determine the physical pixel width of a string.

for example:

FONT_SIZE = 10
str="123456789"
width = str.length * FONT_SIZE  # which will be 9 * 10 = 90px

PROBLEM: But for chinese, japanese or korean:

FONT_SIZE = 10
str="一二三四五六七八九"
width = str.length * FONT_SIZE  # this still result in 90 (9*10)

But it really should be 180 as they are 2 chars with for each char.

How do I make this function (returns true/false)?

def is_wide_char char
  #how to?
end

class String
  def wlength
    l = 0
    self.each{|c| is_wide_char(c)? l+=2: l+=1}
    l
  end
end
Makoto
  • 100,191
  • 27
  • 181
  • 221
c2h2
  • 11,173
  • 13
  • 46
  • 56
  • 1
    Are you really willing to assume that your users are always using fixed-width fonts? – sarnold Feb 21 '11 at 09:49
  • Have a look at http://stackoverflow.com/questions/4681055/how-can-i-detect-cjk-characters-in-a-string-in-ruby – steenslag Feb 21 '11 at 10:06
  • awesome. solved. about the fonts I use RMagick to draw them with fixed font width. So each char will be in a consistent width. – c2h2 Feb 21 '11 at 10:10
  • Also remember that length return the number of chars. Use bytesize if you need the number of bytes – Luis Feb 21 '11 at 11:51

1 Answers1

1

How can I detect CJK characters in a string in Ruby? gives the answer

class String
  def contains_cjk?
    !!(self =~ /\p{Han}|\p{Katakana}|\p{Hiragana}\p{Hangul}/)
  end
end

strings= ['日本', '광고 프로그램', '艾弗森将退出篮坛', 'Watashi ha bakana gaijin desu.']
strings.each{|s| puts s.contains_cjk?}

#true
#true
#true
#false
Community
  • 1
  • 1
c2h2
  • 11,173
  • 13
  • 46
  • 56