如何在drawAtPoint中更改NSString的颜色

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

一切运行良好,但我做了一些布局更改,现在需要绘制的字符串是白色的。使用设置填充颜色和描边颜色的方法没有任何作用。还有其他方法可以实现这个吗?

3个回答

27

在属性中设置前景色,并使用withAttributes函数进行绘制

NSDictionary *attributes = [NSDictionary dictionaryWithObjects:
                            @[font, [UIColor whiteColor]]
                            forKeys:
                            @[NSFontAttributeName, NSForegroundColorAttributeName]];
[string drawInRect:frame withAttributes:attributes];

3
[text drawInRect:CGRectIntegral(rect) withAttributes:@{ NSFontAttributeName: font, NSForegroundColorAttributeName: [UIColor whiteColor] }]; 这行代码会将指定的文本在一个矩形区域内绘制出来,并使用给定的字体和白色前景色。 - Schultz9999
4
至少对于我来说,设置 NSForegroundColorAttributeName 属性起作用了,而被接受的答案中的解决方案并没有起作用。 - aroth

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

好的,搞定了。奇怪,我本来就是这么做的...哦,不管了,问题解决了,谢谢! - RaysonK

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

我已经尝试过CGContextSetFillColorWithColor,以及CGContextSetStrokeColorWithColor。 - RaysonK
1
@RaysonK 我建议使用我的替代方案,因为我认为我也遇到了使用 drawAtPoint 的同样问题,所以最终使用了那个方案。 - Miro Hudak
1
实际上,那个方法调用最终起作用了。不过还是谢谢你的建议。 - RaysonK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接