我的应用程序中有一个选项可以更改按钮的颜色。我使用 UIImage 上的一个类别来做到这一点。我不想用某种颜色对按钮进行着色/刻录,而是用存储在 NSUserDefaults 中的颜色替换所有白色(255、255、255)像素。该按钮是一个具有透明背景的随机播放图标。它看起来像这样,白色替换为红色:
我创建了我的代码:http ://brandontreb.com/image-manipulation-retrieving-and-updating-pixel-values-for-a-uiimage 这是我用来替换像素的代码。我把它放在我的 UIImage 类别中:
-(UIImage *)replaceWhiteWith{
NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"color"];
UIColor *color = [NSString colorFromNSString:str];
return [self replaceWithColor:color];
}
-(UIImage *) replaceWithColor:(UIColor *)color {
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
CGContextRef ctx;
CGImageRef imageRef = [self CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int byteIndex = 0;
for (int ii = 0 ; ii < width * height ; ++ii)
{
if(rawData[byteIndex] == 255 && rawData[byteIndex+1] == 255 && rawData[byteIndex+2] == 255){
rawData[byteIndex] = (red) * 255;
rawData[byteIndex+1] = (green) * 255;
rawData[byteIndex+2] = (blue) * 255;
rawData[byteIndex+3] = (alpha) * 255;
}
byteIndex += 4;
}
ctx = CGBitmapContextCreate(rawData,
CGImageGetWidth( imageRef ),
CGImageGetHeight( imageRef ),
8,
CGImageGetBytesPerRow( imageRef ),
CGImageGetColorSpace( imageRef ),
kCGImageAlphaPremultipliedLast );
imageRef = CGBitmapContextCreateImage (ctx);
UIImage* rawImage = [UIImage imageWithCGImage:imageRef];
CGContextRelease(ctx);
return rawImage;
}