从CALayers绘制图像

Tho*_*asM 1 iphone core-animation core-graphics objective-c quartz-graphics

我正在构建某种审查应用程序.到目前为止,我已经完成了用我的iPhone拍摄的图像像素化.

但我想最终实现这样的图像:http://images-mediawiki-sites.thefullwiki.org/11/4/8/8/8328511755287292.jpg

所以我的想法是完全像素化我的图像,然后在它上面添加一个蒙版,以达到预期的效果.因此,就层次而言,它就像:originalImage + maskedPixelatedVersionOfImage ..我正在考虑在触摸图像时为蒙版设置动画,以将蒙版缩放到所需的大小.手指放在图像上的时间越长,面具就越大......

经过一番搜索,我想这可以使用CALayers和CAAnimation来完成.但是,我如何将这些图层合成到我可以保存在iphone上的photoalbum中的图像?

我在这里采取正确的方法吗?

编辑:

好吧,我觉得Ole的解决方案是正确的,虽然我仍然没有得到我想要的东西:我使用的代码是:

    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();
Run Code Online (Sandbox Code Playgroud)

所以在我的imageView中我做了:setImage,它有照片的原始(未经编辑)版本.最重要的是我添加了一个子图层mosaicLayer,它有一个mask属性:maskLayer.我想通过渲染imageView的rootlayer,一切都会好起来的.这不正确吗?

另外,我想出了别的东西:我的面具被拉伸和旋转,我猜这与imageOrientation有关?我注意到意外地将mosaicLayer保存到我的库中,这也解释了我的问题,掩码似乎掩盖了我的图像的错误部分......

Ole*_*ann 7

要渲染图层树,请将所有图层放在公共容器图层中并调用:

UIGraphicsBeginImageContext(containerLayer.bounds.size);
[containerLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这种方法会阻止您在后台线程上进行渲染.如果您需要线程安全,请避免使用`UI`函数并创建自己的`CGBitmapContext`:http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CGBitmapContext/Reference/reference.html (2认同)