views:

59

answers:

2

I need to create a custom UILabel to display some dynamic multiline text. The text color is white on a black background. But the background should only be visible right behind the text to simulate the effect of an selected text area.

I started with subclassing UILabel and overriding drawTextInRect to do my own drawings.

- (void) drawTextInRect:(CGRect)rect
{
 /* do some custom drawings here */

 [super drawTextInRect:rect];
}

So far i could not figure out a way to compute the text-bounds do draw my background into. Does anybody now how do do this kind of stuff? Thanks a lot.

A: 

NSString has some additions in UIKit to allow for calculating the size used to render the string, given various parameters. You can use these methods to calculate the size the UILabel needs to render the string, and then resize the UILabel to precisely this size. Look in the documentation for a method called -sizeWithFont:, all of the other variations are listed there. Make sure you use the right method to match how your UILabel is configured.

There is one caveat here, which is that on iOS 4, there is a bug where these methods actually return a slightly different size than is actually used for drawing (at least for the system font on iPhone 4's [e.g. Helvetica Neue], I don't know if this bug affects any other fonts). Unfortunately the only workaround I know of is to switch to Core Text for all your text rendering, so you may just prefer to live with this bug (if it even affects you) until Apple pushes out a software update. This bug does affect Apple's own applications so there is plenty of precedent for not handling it.

Kevin Ballard
A: 

Ok. Now after some input from stackoverflow i am using this code snippet to get the textbounds but it only works fine with single line text.

- (void) drawTextInRect:(CGRect)rect
{
    CGFloat lineHeight  = [self.text sizeWithFont:self.font].height;
    CGSize  testSize    = CGSizeMake(320, lineHeight * self.numberOfLines);
    CGSize  textSize    = [self.text sizeWithFont:self.font constrainedToSize:testSize lineBreakMode:self.lineBreakMode];

    //NSLog(@"drawTextInRect lineHeight %f, width %f x height %f", lineHeight, textSize.width, textSize.height);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextAddRect(context, CGRectMake(0, 0, textSize.width, textSize.height));
    CGContextFillPath(context);

    CGContextRestoreGState(context);

    [super drawTextInRect:rect];
}

If i have multiline text i still need some code to compute the path-information of the text and not just the bounding rect so that i can use CGContextDrawPath to draw my background. Any thoughts on that? Thanks.

loopmasta