Saturday, December 12, 2009

Cocoa and Drawing truncated text

To properly allow for long names of objects in the time-line I need to draw truncated text.
Untruncated Text

What I mean is that I want to truncate the text if the area is to small for the text and then to have some ellipses that show where the truncation occurs. This was second nature to me in my days as a ToolBox (Carbon) programmer but fathoming it out under Cocoa tool a while. Whatever I tried failed - and it seemed that the Apple docs failed me.

In a tight corner Google is a good friend and I found the blog-post from Preston Jackson. It is an example of the kind of blog-post I find most useful. A problem and a solution - with a code snippet. Thanks Preston.

I copy/pasted his code and it worked. Then I integrated it into the code that should have worked but didn't and it failed. It took (unbelievably) an hour to get to the bottom of the problem. In full numpty horror I realized that I was calculating the width of the text I was and changing my destination rectangle so it would be that width.

With the truncation the text looks like this:

No comments: