如何在drawAtPoint中更改NSString的颜色

Ray*_*onK 12 objective-c ios

我在这里有一大块代码,它在一个字符串上绘制一个字符串:

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]];
Run Code Online (Sandbox Code Playgroud)

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

Gap*_*app 27

在属性中设置foregroundcolor,并使用draw withAttributes函数

NSDictionary *attributes = [NSDictionary dictionaryWithObjects:
                            @[font, [UIColor whiteColor]]
                            forKeys:
                            @[NSFontAttributeName, NSForegroundColorAttributeName]];
[string drawInRect:frame withAttributes:attributes];
Run Code Online (Sandbox Code Playgroud)

  • 至少对我来说,设置`NSForegroundColorAttributeName`属性工作正常,而接受的答案中的解决方案没有. (4认同)
  • 或者`[text drawInRect:CGRectIntegral(rect)withAttributes:@ {NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor whiteColor]}];` (3认同)

Mic*_*son 9

你有没有尝试过:

CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), textColor);
Run Code Online (Sandbox Code Playgroud)

例如:

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]];
Run Code Online (Sandbox Code Playgroud)


Mir*_*dak 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);
}
Run Code Online (Sandbox Code Playgroud)