3 回答

TA貢獻1719條經驗 獲得超6個贊
-(void)changeColor
{
UIImage *temp23=[UIImage imageNamed:@"leaf.png"];
CGImageRef ref1=[self createMask:temp23];
const float colorMasking[6] = {1.0, 2.0, 1.0, 1.0, 1.0, 1.0};
CGImageRef New=CGImageCreateWithMaskingColors(ref1, colorMasking);
UIImage *resultedimage=[UIImage imageWithCGImage:New];
}
-(CGImageRef)createMask:(UIImage*)temp
{
CGImageRef ref=temp.CGImage;
int mWidth=CGImageGetWidth(ref);
int mHeight=CGImageGetHeight(ref);
int count=mWidth*mHeight*4;
void *bufferdata=malloc(count);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGContextRef cgctx = CGBitmapContextCreate (bufferdata,mWidth,mHeight, 8,mWidth*4, colorSpaceRef, kCGImageAlphaPremultipliedFirst);
CGRect rect = {0,0,mWidth,mHeight};
CGContextDrawImage(cgctx, rect, ref);
bufferdata = CGBitmapContextGetData (cgctx);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bufferdata, mWidth*mHeight*4, NULL);
CGImageRef savedimageref = CGImageCreate(mWidth,mHeight, 8, 32, mWidth*4, colorSpaceRef, bitmapInfo,provider , NULL, NO, renderingIntent);
CFRelease(colorSpaceRef);
return savedimageref;
}
以上代碼經過測試,我通過使用遮罩將綠色更改為紅色

TA貢獻1816條經驗 獲得超6個贊
這是yubenyi的代碼的一項調整,可以多次使用。通過將圖像轉換為未壓縮的jpeg,它將在處理之前剝離alpha通道。還添加了一些有關顏色范圍選擇如何工作的注釋。
-(UIImage *)changeWhiteColorTransparent: (UIImage *)image
{
//convert to uncompressed jpg to remove any alpha channels
//this is a necessary first step when processing images that already have transparency
image = [UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)];
CGImageRef rawImageRef=image.CGImage;
//RGB color range to mask (make transparent) R-Low, R-High, G-Low, G-High, B-Low, B-High
const double colorMasking[6] = {222, 255, 222, 255, 222, 255};
UIGraphicsBeginImageContext(image.size);
CGImageRef maskedImageRef=CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
//iPhone translation
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);
CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
CGImageRelease(maskedImageRef);
UIGraphicsEndImageContext();
return result;
}
- 3 回答
- 0 關注
- 792 瀏覽
添加回答
舉報