12

我在这里有这段代码,它绘制了一个带有一个字符串的块:

CGContextDrawImage(context, CGRectMake([blok getLocation].x * xunit, [blok getLocation].y * yunit, 40, 40), [blok getImage].CGImage);
[[blok getSymbol] drawAtPoint:CGPointMake([blok getLocation].x * xunit+15, [blok getLocation].y * yunit) withFont:[UIFont fontWithName:@"Helvetica" size:24]];

它工作正常,但我一直在做一些布局更改,现在我需要它以便绘制的字符串是白色的。使用设置填充颜色和描边颜色的方法没有做任何事情。还有其他方法可以做到这一点吗?

4

3 回答 3

27

在属性中设置前景色并使用draw withAttributes函数

NSDictionary *attributes = [NSDictionary dictionaryWithObjects:
                            @[font, [UIColor whiteColor]]
                            forKeys:
                            @[NSFontAttributeName, NSForegroundColorAttributeName]];
[string drawInRect:frame withAttributes:attributes];
于 2014-02-21T16:52:16.367 回答
9

你有没有尝试过:

CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), textColor);

例如:

CGContextDrawImage(context, CGRectMake([blok getLocation].x * xunit, [blok getLocation].y * yunit, 40, 40), [blok getImage].CGImage);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), textColor);
[[blok getSymbol] drawAtPoint:CGPointMake([blok getLocation].x * xunit+15, [blok getLocation].y * yunit) withFont:[UIFont fontWithName:@"Helvetica" size:24]];
于 2012-07-31T22:49:03.920 回答
7

这是我用于绘制标签的:

- (void)_drawLabel:(NSString *)label withFont:(UIFont *)font forWidth:(CGFloat)width 
           atPoint:(CGPoint)point withAlignment:(UITextAlignment)alignment color:(UIColor *)color
{
    // obtain current context
    CGContextRef context = UIGraphicsGetCurrentContext();

    // save context state first
    CGContextSaveGState(context);

    // obtain size of drawn label
    CGSize size = [label sizeWithFont:font 
                             forWidth:width 
                        lineBreakMode:UILineBreakModeClip];

    // determine correct rect for this label
    CGRect rect = CGRectMake(point.x, point.y - (size.height / 2),
                             width, size.height);

    // set text color in context
    CGContextSetFillColorWithColor(context, color.CGColor);

    // draw text
    [label drawInRect:rect
             withFont:font
        lineBreakMode:UILineBreakModeClip
            alignment:alignment];

    // restore context state
    CGContextRestoreGState(context);
}
于 2012-07-31T22:50:18.703 回答