我有一个UIView,我想保存为UI
Image.我使用UIGraphicsBeginImageContext这样做,它可以正常工作.但是当我对(view / layer.mask)中的图像应用蒙版时,我通过UIGraphicsBeginImageContext捕获的图像是错误的(运行应用程序时屏蔽是正常的,但是当尝试从UIView获取UIImage时).有人遇到类似的问题吗?
解决方法
如果我理解正确,您希望从UIView层创建一个UIImage,而该层被屏蔽.我假设你想让目标UIImage拥有透明的背景.
我没有遇到任何实施这个问题,我有一个演示项目,你可以看看:
https://bitbucket.org/reydan/so_imagemask
您首先需要按面罩按钮.它将从束中加载掩码图像(黑色和白色),并将其设置为上面的UIView容器的图层蒙版.
然后,您可以按下将UIView容器转换为UIImage的复制图像按钮,然后将其设置为下面的目标图像视图,以查看结果.
我也会在这里发布两种方法:
- (IBAction)onMask:(id)sender { UIImage* maskImage = [UIImage imageNamed:@"star.png"]; UIImageView* maskImageView = [[UIImageView alloc] initWithImage:maskImage]; maskImageView.contentMode = UIViewContentModeScaleAspectFit; maskImageView.frame = _mainContainerView.bounds; _mainContainerView.layer.mask = maskImageView.layer; } - (IBAction)onCopyImage:(id)sender { UIGraphicsBeginImageContextWithOptions(_mainContainerView.bounds.size,FALSE,[[UIScreen mainScreen] scale]); [_mainContainerView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); _destImageView.image = img; }
编辑
显然renderInContext:在IOS6上不使用掩码(因为它也在这里说SO).
我的解决办法是手动将蒙版应用于图像.掩码是从该层的掩码属性中获取的,并且在上下文中渲染,因此我们对transformations / contentModes / etc没有任何问题.
这是更新的源代码(它也可在bitbucket上获得):
- (IBAction)onCopyImage:(id)sender { // Get the image from the mainImageView UIGraphicsBeginImageContextWithOptions(_mainContainerView.bounds.size,[[UIScreen mainScreen] scale]); [_mainContainerView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Use the next block if targeting IOS6 { // Manually create a mask image (taken from the mask layer) UIGraphicsBeginImageContextWithOptions(_mainContainerView.bounds.size,TRUE,[[UIScreen mainScreen] scale]); CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(ctx,[UIColor whiteColor].CGColor); CGContextFillRect(ctx,_mainContainerView.bounds); [_mainContainerView.layer.mask renderInContext:ctx]; UIImage * maskimg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // Create a image mask from the UIImage CGImageRef maskRef = maskimg.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),CGImageGetHeight(maskRef),CGImageGetBitsPerComponent(maskRef),CGImageGetBitsPerPixel(maskRef),CGImageGetBytesPerRow(maskRef),CGImageGetDataProvider(maskRef),NULL,false); // Apply the mask to our source image CGImageRef maskedimg= CGImageCreateWithMask(img.CGImage,mask); // Convert to UIImage so we can easily display it in a UIImageView img = [UIImage imageWithCGImage:maskedimg scale:img.scale orientation:img.imageOrientation]; CGImageRelease(mask); CGImageRelease(maskedimg); } _destImageView.image = img; }
编辑请检查bitbucket上的最新项目,因为它包含最新版本.