我有这段代码:
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”的背景颜色(黑色)来填充给定的矩形,这样它就是一个文本居中的大黑条。这可能吗?
答案 0 :(得分:0)
正如@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);
这给出了结果: