在UIIMage上用透明替换绿色

时间:2013-01-30 16:20:48

标签: ios cocoa-touch uiimage core-graphics

我用我的UIImage绘制绿线:CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),0,1,0,1);

效果很好

但在我想用透明的

替换我的绿色笔画之后

我使用这个功能:

    - (UIImage*) replaceColor:(UIColor*)color inImage:(UIImage*)image withTolerance:(float)tolerance {
CGImageRef imageRef = [image CGImage];

NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
NSUInteger bitmapByteCount = bytesPerRow * height;

unsigned char *rawData = (unsigned char*) calloc(bitmapByteCount, sizeof(unsigned char));

CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                             bitsPerComponent, bytesPerRow, colorSpace,
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

CGColorRef cgColor = [color CGColor];
const CGFloat *components = CGColorGetComponents(cgColor);
float r = components[0];
float g = components[1];
float b = components[2];
//float a = components[3]; // not needed

r = r * 255.0;
g = g * 255.0;
b = b * 255.0;

const float redRange[2] = {
    MAX(r - (tolerance / 2.0), 0.0),
    MIN(r + (tolerance / 2.0), 255.0)
};

const float greenRange[2] = {
    MAX(g - (tolerance / 2.0), 0.0),
    MIN(g + (tolerance / 2.0), 255.0)
};

const float blueRange[2] = {
    MAX(b - (tolerance / 2.0), 0.0),
    MIN(b + (tolerance / 2.0), 255.0)
};

int byteIndex = 0;

while (byteIndex < bitmapByteCount) {
    unsigned char red   = rawData[byteIndex];
    unsigned char green = rawData[byteIndex + 1];
    unsigned char blue  = rawData[byteIndex + 2];

    if (((red >= redRange[0]) && (red <= redRange[1])) &&
        ((green >= greenRange[0]) && (green <= greenRange[1])) &&
        ((blue >= blueRange[0]) && (blue <= blueRange[1]))) {
        // make the pixel transparent
        //
        rawData[byteIndex] = 0;
        rawData[byteIndex + 1] = 0;
        rawData[byteIndex + 2] = 0;
        rawData[byteIndex + 3] = 0;
    }

    byteIndex += 4;
}

UIImage *result = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];

CGContextRelease(context);
free(rawData);

return result;
    }

我在How to make one color transparent on a UIImage?

上找到了

我不知道为什么但是位于笔画边框的所有绿色像素仍在UIImage中

有什么想法吗?

这是结果图片(笔划的路径在中间,你可以看到周围的绿色像素)

enter image description here

提前致谢

0 个答案:

没有答案