2017-07-30 55 views

回答

0

,如果你想改變單個像素這個答案只適用..

首先使用UIImage.cgImage獲得CGImage。接下來,使用CGBitmapContextCreateCGColorSpaceCreateDeviceRGB色彩空間以及您想要的任何混合模式創建位圖上下文。

然後調用CGContextDrawImage將圖像繪製到由您提供的像素數組支持的上下文。清理,你現在有一個像素陣列。

- (uint8_t*)getPixels:(UIImage *)image { 
    CGColorSpaceRef cs= CGColorSpaceCreateDeviceRGB(); 
    uint8_t *pixels= malloc(image.size.width * image.size.height * 4); 
    CGContextRef ctx= CGBitmapContextCreate(rawData, image.size.width, image.size.height, 8, image.size.width * 4, cs, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
    CGColorSpaceRelease(cs); 

    CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height)); 
    CGContextRelease(ctx); 
    return pixels; 
} 

,但是你想修改的像素。然後重新從像素的圖像..

- (UIImage *)imageFromPixels:(uint8_t *)pixels width:(NSUInteger)width height:(NSUInteger)height { 
    CGDataProviderRef provider = CGDataProviderCreateWithData(nil, pixels, width * height * 4, nil); 

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); 
    CGImageRef cgImageRef = CGImageCreate(width, height, 8, 32, width * 4, cs, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast, provider, nil, NO, kCGRenderingIntentDefault); 

    pixels = malloc(width * height * 4); 
    CGContextRef ctx = CGBitmapContextCreate(pixels, width, height, 8, width * 4, cs, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast); 

    CGContextDrawImage(ctx, (CGRect) { .origin.x = 0, .origin.y = 0, .size.width = width, .size.height = height }, cgImage); 
    CGImageRef cgImage = CGBitmapContextCreateImage(ctx); 
    UIImage *image = [UIImage imageWithCGImage:cgImage]; 
    CGImageRelease(cgImage); 
    CGContextRelease(ctx); 
    CGColorSpaceRelease(cs); 
    CGImageRelease(cgImageRef); 
    CGDataProviderRelease(provider); 
    free(pixels); 
    return image; 
} 
+0

感謝,但我完成我的工作CIFilter,:Q –

0

其中一種方法是使用圖像作爲模板並設置所需的顏色。

extension UIImageView { 
func changeImageColor(color:UIColor) -> UIImage 
{ 
    image = image!.withRenderingMode(.alwaysTemplate) 
    tintColor = color 
    return image! 
} 
} 

    //Change color of logo 
    logoImage.image = logoImage.changeImageColor(color: .red) 
相關問題