绘制一个带有背景色的 NSString 来填充矩形

Drawing an NSString with background color to fill rect

我有这个代码:

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}];

产生这样的东西:

我想要的是 "GA" 的背景颜色(黑色)填充给定的矩形,这样它就是一个大黑条,文本居中。这可能吗?

正如@beyowulf 所建议的那样。使用 UIBezierPath 绘制矩形,然后用字符串填充它。

    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);

这给出了结果: