views:

191

answers:

2

My code is

-(UIImage *)addText:(UIImage *)img text:(NSString *)text1
{
    int w = img.size.width;
    int h = img.size.height; 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

    char* text = (char *)[text1 cStringUsingEncoding:NSASCIIStringEncoding];
    CGContextSelectFont(context, "Arial", 18, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);

    CGContextSetRGBFillColor(context, 255, 255, 255, 2);

    CGContextShowTextAtPoint(context, 10, 170, text, strlen(text));

    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return [UIImage imageWithCGImage:imageMasked];
}

How can we change the color of the text programmatically? Answers will be greatly appreciated!

+1  A: 

My guess is just change the last instance of CGContextSetRGBFillColor to the RGB value you'd like. Right now it's white. Change the 255, 255, 255 part to the corresponding RGB value you'd like (0.0 - 1.0 range per color channel). ie. Red would be 1.0, 0.0, 0.0; Blue 0.0, 0.0, 1.0, Yellow 1.0, 1.0, 0; Black 0.0, 0.0, 0.0; etc.... Good luck

Edit: range is 0.0-1.0 not 0-255

Adolfo
That's not the range of the arguments to the `CGContextSetRGBFillColor` function.
Peter Hosey
You're right, 0-1.0. I'll edit it.
Adolfo
Thanks a lot!! Now I got it.
iSharreth
+1  A: 
CGContextSetRGBFillColor(context, 255, 255, 255, 2);

How can we change the color of the text programmatically?

That's one way, although you're doing it wrong. See the documentation; all four of those values are out of range, with three of them being way out of range.

Peter Hosey
Thanks a lot!! Now I got it.
iSharreth