Ios 使用背景色绘制NSString以填充rect

Ios 使用背景色绘制NSString以填充rect,ios,objective-c,core-text,Ios,Objective C,Core Text,我有以下代码: NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; style.alignment = NSTextAlignmentCenter; [ticketName.uppercaseString drawInRect:CGRectMake(xPos, yPos, badgeSize.width - UIBarcode.size.width, 44) withAt

我有以下代码:

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对rect进行daw,然后用字符串填充它

    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);
结果如下:


尝试添加空白并用它们绘制。使用
uibeziercrove
绘制矩形,填充矩形,然后绘制字符串。如果您知道应该绘制字符串的位置,这很容易。(在本例中,您可以简单地使用两个视图。)通常您不知道这一点。