我会尽可能的简单.
如何在iOS中的CALayers上创建反向掩码?
我有一个红色的视图和一个用来掩盖红色视图的图像.
我使用视图的CALayer掩码属性应用掩码,结果如下.
不过我希望的是相反的结果,比如说
(想象这里的白色部分实际上是背景中的木头,因为我对图像编辑软件不是很好)
解决方法
希望有帮助
步骤1:创建没有任何Alpha通道的掩码.
步骤2:通过以下方法创建反转掩码
- (UIImage*) createInvertMask:(UIImage *)maskImage withTargetImage:(UIImage *) image { CGImageRef maskRef = maskImage.CGImage; CGBitmapInfo bitmapInfo = kCGImageAlphaNone; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; CGImageRef mask = CGImageCreate(CGImageGetWidth(maskRef),CGImageGetHeight(maskRef),CGImageGetBitsPerComponent(maskRef),CGImageGetBitsPerPixel(maskRef),CGImageGetBytesPerRow(maskRef),CGColorSpaceCreateDeviceGray(),bitmapInfo,CGImageGetDataProvider(maskRef),nil,NO,renderingIntent); CGImageRef masked = CGImageCreateWithMask([image CGImage],mask); CGImageRelease(mask); CGImageRelease(maskRef); return [UIImage imageWithCGImage:masked]; }
步骤3:通过以下方法将反向掩码设置为UIView
-(void) maskWithImage:(UIImage*) maskImage TargetView:(UIView*) targetView{ CALayer *_maskingLayer = [CALayer layer]; _maskingLayer.frame = targetView.bounds; [_maskingLayer setContents:(id)[maskImage CGImage]]; [targetView.layer setMask:_maskingLayer]; }
成品.
怎么打电话
UIImage* targetImage = [UIImage imageNamed:@"sky_bg.png"]; UIImage* mask = [UIImage imageNamed:@"mask01.png"]; UIImage* invertMask = [self createInvertMask:mask withTargetImage:targetImage]; [self maskWithImage:invertMask TargetView:targetview];