0

我在我的 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;
    }

我在如何使 UIImage 上的一种颜色透明?

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

任何想法 ?

这是结果图(描边的路径在中间,可以看到周围有一些绿色像素)

在此处输入图像描述

提前致谢

4

0 回答 0