下面是我的简单解决方案,它可以让你达到 80% 的准确率,非常适合我的目的。它仅适用于 Arial 并且假定为 12 pt 字体,但它也可能与其他字体成比例。
def getApproximateArialStringWidth(st):
size = 0 # in milinches
for s in st:
if s in 'lij|\' ': size += 37
elif s in '![]fI.,:;/\\t': size += 50
elif s in '`-(){}r"': size += 60
elif s in '*^zcsJkvxy': size += 85
elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
elif s in 'BSPEAKVXY&UwNRCHD': size += 112
elif s in 'QGOMm%W@': size += 135
else: size += 50
return size * 6 / 1000.0 # Convert to picas
如果你想截断一个字符串,这里是:
def truncateToApproximateArialWidth(st, width):
size = 0 # 1000 = 1 inch
width = width * 1000 / 6 # Convert from picas to miliinches
for i, s in enumerate(st):
if s in 'lij|\' ': size += 37
elif s in '![]fI.,:;/\\t': size += 50
elif s in '`-(){}r"': size += 60
elif s in '*^zcsJkvxy': size += 85
elif s in 'aebdhnopqug#$L+<>=?_~FZT' + string.digits: size += 95
elif s in 'BSPEAKVXY&UwNRCHD': size += 112
elif s in 'QGOMm%W@': size += 135
else: size += 50
if size >= width:
return st[:i+1]
return st
然后是以下内容:
>> width = 15
>> print truncateToApproxArialWidth("the quick brown fox jumps over the lazy dog", width)
the quick brown fox jumps over the
>> print truncateToApproxArialWidth("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG", width)
THE QUICK BROWN FOX JUMPS
渲染时,这些字符串的宽度大致相同:
敏捷的棕色狐狸跳过
快速的棕色狐狸跳跃