Search code examples
iphonestringdrawrect

How to draw box containing string when using drawInRect?


I am using drawInRect from UIKit to draw a string. I want to also draw (see) the bounding rectangle where the string is drawn (sort of having a string inside a box). How to do this?


Solution

  • The drawInRect UIKit methods return a CGSize, which is the size of the drawn string. Use this together with the origin of the CGRect you passed to drawInRect, and that is the rect you want to draw.

    CGSize size = [string drawInRect:rect .... plus your options];
    CGRect boundingRect = rect;
    boundingRect.size = size;
    
    [[UIBezierPath bezierPathWithRect:boundingRect] stroke];