【问题标题】:In a UIImage (or its derivatives), how can I replace one color with another?在 UIImage(或其衍生物)中,如何用另一种颜色替换一种颜色?
【发布时间】:2009-08-11 21:43:26
【问题描述】:

例如,我有一个 UIImage(如果需要,我可以从中获取 CGImage、CGLayer 等),我想用蓝色 (0, 0, 1)。

我有代码来确定哪些像素是目标颜色(请参阅this SO question & answer),我可以在 rawData 中替换适当的值,但是 (a) 我不确定如何从我的 rawData 缓冲区取回 UIImage并且 (b) 似乎我可能缺少一个可以自动为我完成所有这些的内置程序,从而为我省去了很多悲伤。

谢谢!

【问题讨论】:

    标签: iphone colors uiimage


    【解决方案1】:

    好的,所以我们将 UIImage 放入 rawBits 缓冲区(参见原始问题中的链接),然后我们根据自己的喜好调整缓冲区中的数据(即,将所有红色分量(每 4 个字节)设置为 0,作为测试),现在需要获取一个新的 UIImage 来表示旋转后的数据。

    我在Erica Sudan's iPhone Cookbook,第 7 章(图像),示例 12(位图)中找到了答案。相关调用为CGBitmapContextCreate(),相关代码为:

    + (UIImage *) imageWithBits: (unsigned char *) bits withSize: (CGSize)  
    size
    {
        // Create a color space
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        if (colorSpace == NULL)
        {
            fprintf(stderr, "Error allocating color space\n");
            free(bits);
            return nil;
        }
    
        CGContextRef context = CGBitmapContextCreate (bits, size.width,  
    size.height, 8, size.width * 4, colorSpace,  
    kCGImageAlphaPremultipliedFirst);
        if (context == NULL)
        {
            fprintf (stderr, "Error: Context not created!");
            free (bits);
            CGColorSpaceRelease(colorSpace );
            return nil;
        }
    
        CGColorSpaceRelease(colorSpace );
        CGImageRef ref = CGBitmapContextCreateImage(context);
        free(CGBitmapContextGetData(context));
        CGContextRelease(context);
    
        UIImage *img = [UIImage imageWithCGImage:ref];
        CFRelease(ref);
        return img;
    }
    

    希望这对未来的网站探索者有用!

    【讨论】:

    • 可惜没有多少人使用这种功能,你值得更多的功劳。
    猜你喜欢
    • 2014-05-07
    • 2015-02-12
    • 2017-10-05
    • 2013-06-09
    • 2019-07-06
    • 2015-12-19
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多