【问题标题】:How can we change color of a text programmatically?我们如何以编程方式更改文本的颜色?
【发布时间】:2010-03-24 03:58:18
【问题描述】:

我的代码是

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

我们如何以编程方式更改文本的颜色? 答案将不胜感激!

【问题讨论】:

    标签: iphone objective-c core-graphics


    【解决方案1】:

    我的猜测是将CGContextSetRGBFillColor 的最后一个实例更改为您想要的RGB 值。现在是白色的。将 255、255、255 部分更改为您想要的相应 RGB 值(每个颜色通道 0.0 - 1.0 范围)。 IE。红色将是 1.0、0.0、0.0;蓝色 0.0、0.0、1.0、黄色 1.0、1.0、0;黑色 0.0、0.0、0.0;等等......祝你好运

    编辑:范围是 0.0-1.0 而不是 0-255

    【讨论】:

    • 这不是CGContextSetRGBFillColor 函数的参数范围。
    【解决方案2】:
    CGContextSetRGBFillColor(context, 255, 255, 255, 2);
    

    我们如何以编程方式更改文本的颜色?

    这是一种方式,尽管你做错了。见the documentation;所有这四个值都超出范围,其中三个超出范围方式

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2015-12-06
      相关资源
      最近更新 更多