更改UIImage或UIGraphics的文本颜色

时间:2014-07-10 00:39:02

标签: ios uiimage

我将实现模块,将白色数字添加到正在ios应用上绘制的UIImage的箭头上。在执行时,它表明在数字上只设置了黑色。我添加了

CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [UIColor whiteColor].CGColor);

但无济于事。你能告诉我哪个更好的方法吗?

以下是我的工作

-(UIImage*) drawText:(NSString*) text
             inImage:(UIImage*)  image
             atPoint:(CGPoint)   point
{
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
    [[UIColor whiteColor] set];

    UIFont *font = [UIFont boldSystemFontOfSize:24];

    if([text respondsToSelector:@selector(drawInRect:withAttributes:)])
    {
        //IOS 7
        NSDictionary *att = @{NSFontAttributeName:font};
        [text drawInRect:rect withAttributes:att];
    }
    else
    {
        [text drawInRect:CGRectIntegral(rect) withFont:font];

    }
    CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [UIColor whiteColor].CGColor);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

1 个答案:

答案 0 :(得分:2)

根据您想要的时间长短,选择这3种解决方案中的任何一种。 6+和7+版本使用NSForegroundColorAttributeName来选择颜色。这些是首选方法。

iOS 7 +

// (add the color to the attribute)
NSDictionary *att = @{NSFontAttributeName           :font,
                      NSForegroundColorAttributeName:[UIColor whiteColor]};
[@"test" drawInRect:rect withAttributes:att];

iOS 6 + (也适用于iOS 7)

// (add the color to the attribute, using NSAttributedString)
NSDictionary *att = @{NSFontAttributeName           :font,
                      NSForegroundColorAttributeName:[UIColor whiteColor]};
NSAttributedString * text = [[NSAttributedString alloc] initWithString:@"test"
                                                            attributes:att];
[text drawInRect:rect];

iOS 5 (在iOS 7上无效)

// No attributes involved
[[UIColor whiteColor] set];
[@"test" drawInRect:CGRectIntegral(rect) withFont:font];