Jruby trim string based on length with ellipses
This is a pretty specific problem, but I'm wondering if anyone has a brilliant solution. I'm trying to set a fixed font size string to a custom size box, so if the whole string doesn't fit, I want to crop it and declare an ellipse (...).
So, if my text is "netherlands", I want to define how much of that fits in my custom size box to look like "bottom ..."
I am using jruby so java or ruby ββis ok. I can't think of a fantastic solution other than trimming / testing the char -by- char to see if the string fits. Since this is not a fixed width font, I cannot just take each char as the same width, which would make this much easier.
Any thoughts or clues that might point me in the right direction?
source to share
The character character is probably just fine. But if you are making billions of them and you need to speed them up, you can binary search for the correct length rather than just iterating through characters. Here is a generic binary_search method that you can call Integer. Give it a comparison block <=> that returns -x 0 or + x, and it iteratively jumps by half each time until none of the tests return 0, or the transition size gets too small.
class Integer
def binary_search
current = self
nextjump = current / 2.0
until (test = yield(current)) == 0 || nextjump < 0.5
if test < 0
current += nextjump
else
current -= nextjump
end
nextjump /= 2.0
end
current
end
end
Then use it like this:
goal = whatever a[0...(a.size.binary_search {|i| a[0...i].stringWidth - goal})]
source to share
An alternative approach would be to handle display truncation in CSS!
<div style="border: 1px solid gray; width: 200px;">
<span style="float: right; color: gray">...</span>
<div style="width: 184px; overflow: hidden; white-space: nowrap">
This is a really long string that goes on and on and on and we need to do something about it eventually but for now it just isn't important so I don't want to think about it.
</div></div>
This saves you the thankless task of worrying about your users' browser font metrics (which you don't know and to which your Java server font metrics thus have an unknown relationship).
source to share
take a look at the java FontMetrics class and in particular the stringWidth method.
source to share