2016-06-24 138 views
-1

我有這樣的代碼:繪製一個NSString與背景顏色來填充矩形

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

產生這樣的:

enter image description here

我要的是背景色(黑色)的「GA」填充給定的矩形,這樣它的一個黑色的大條,文字居中。這可能嗎?

+0

嘗試添加空格,並吸引他們。 –

+0

使用「UIBezierCurve」繪製矩形,填充該矩形,然後繪製字符串。 – beyowulf

回答

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

這給出結果:

enter image description here

+0

那麼,如果你知道應該繪製字符串的地方,那很容易。 (在這種情況下,你可以簡單地使用兩個視圖。)通常你不知道這一點。 –