Search code examples
iosobjective-ccore-text

Drawing an NSString with background color to fill rect


I have this code:

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
[ticketName.uppercaseString drawInRect:CGRectMake(xPos, yPos, badgeSize.width - UIBarcode.size.width, 44) withAttributes:@{NSFontAttributeName: FONT_NORMALX(40), NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor blackColor], NSParagraphStyleAttributeName: style}];

That produces something like this:

enter image description here

What I want is for the background color (black) of "GA" to fill the given rect, such that its a big black bar with the text centered inside. Is this possible?


Solution

  • As @beyowulf suggested. USe UIBezierPath to daw the rect and then fill it with the string.

        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // Text Drawing
        CGRect textRect = //bezier Rect
        UIBezierPath* textPath = [UIBezierPath bezierPathWithRect: textRect];
        [UIColor.blackColor setFill];
        [textPath fill];
    
            NSString* textContent = @"GA";
            NSMutableParagraphStyle* textStyle = [NSMutableParagraphStyle new];
            textStyle.alignment = NSTextAlignmentCenter;
    
            NSDictionary* textFontAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize: UIFont.smallSystemFontSize], NSForegroundColorAttributeName: UIColor.whiteColor, NSParagraphStyleAttributeName: textStyle};
    
            CGFloat textTextHeight = [textContent boundingRectWithSize: CGSizeMake(textRect.size.width, INFINITY)  options: NSStringDrawingUsesLineFragmentOrigin attributes: textFontAttributes context: nil].size.height;
            CGContextSaveGState(context);
            CGContextClipToRect(context, textRect);
            [textContent drawInRect: CGRectMake(CGRectGetMinX(textRect), CGRectGetMinY(textRect) + (CGRectGetHeight(textRect) - textTextHeight) / 2, CGRectGetWidth(textRect), textTextHeight) withAttributes: textFontAttributes];
            CGContextRestoreGState(context);
    

    This gives the result:

    enter image description here