ios中图像上的像素化​​图层

时间:2015-03-02 11:56:54

标签: ios objective-c iphone core-graphics

我需要在UIImage上添加像素化的矩形层,可以撤消。 Just like this.

我使用了这段代码,但它没有做我需要的相同的事情

    CALayer *maskLayer = [CALayer layer];
    CALayer *mosaicLayer = [CALayer layer];

    // Mask image ends with 0.15 opacity on both sides. Set the background color of the layer
    // to the same value so the layer can extend the mask image.
    mosaicLayer.contents = (id)[img CGImage];
    mosaicLayer.frame = CGRectMake(0,0, img.size.width, img.size.height);
    UIImage *maskImg = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"mask" ofType:@"png"]];
    maskLayer.contents = (id)[maskImg CGImage];
    maskLayer.frame = CGRectMake(100,150, maskImg.size.width, maskImg.size.height);

    mosaicLayer.mask = maskLayer;

    [imageView.layer addSublayer:mosaicLayer];

    UIGraphicsBeginImageContext(imageView.layer.bounds.size);
    [imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *saver = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

iOS上是否有任何内置的过滤器?请指导我谢谢

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

我们可以使用GPUImage框架,但更好的是使用iOS自己的过滤器。简单编码:))

- (UIImage *)applyCIPixelateFilter:(UIImage*)fromImage withScale:(double)scale
{
    /*
     Makes an image blocky by mapping the image to colored squares whose color is defined by the replaced pixels.
     Parameters

     inputImage: A CIImage object whose display name is Image.

     inputCenter: A CIVector object whose attribute type is CIAttributeTypePosition and whose display name is Center.
     Default value: [150 150]

     inputScale: An NSNumber object whose attribute type is CIAttributeTypeDistance and whose display name is Scale.
     Default value: 8.00
     */
    CIContext *context = [CIContext contextWithOptions:nil];
    CIFilter *filter= [CIFilter filterWithName:@"CIPixellate"];
    CIImage *inputImage = [[CIImage alloc] initWithImage:fromImage];
    CIVector *vector = [CIVector vectorWithX:fromImage.size.width /2.0f Y:fromImage.size.height /2.0f];
    [filter setDefaults];
    [filter setValue:vector forKey:@"inputCenter"];
    [filter setValue:[NSNumber numberWithDouble:scale] forKey:@"inputScale"];
    [filter setValue:inputImage forKey:@"inputImage"];

    CGImageRef cgiimage = [context createCGImage:filter.outputImage fromRect:filter.outputImage.extent];
    UIImage *newImage = [UIImage imageWithCGImage:cgiimage scale:1.0f orientation:fromImage.imageOrientation];

    CGImageRelease(cgiimage);

    return newImage;
}