我有一个背景UIImage,我想用自定义形状裁剪背景UIImage,这样这个背景图像只能通过自定义形状“显示”。例如,我有一个月亮形状的自定义形状,我希望背景图像只能通过月亮形状的部分。
基于另一个答案,我试图在图像上强加一个掩码:
- (UIImage *)createImageFromImage:(UIImage *)image
withMaskImage:(UIImage *)mask {
CGImageRef imageRef = image.CGImage;
CGImageRef maskRef = mask.CGImage;
CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
NULL,
YES);
CGImageRef maskedReference = CGImageCreateWithMask(imageRef, imageMask);
CGImageRelease(imageMask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
CGImageRelease(maskedReference);
return maskedImage;
}
关于如何解决作物问题的任何想法都将非常感激。谢谢!
答案 0 :(得分:2)
在您的背景图片上,您必须通过CALayer
添加自定义蒙版。
请记住,您在mask.png(月亮)中着色的所有内容都将可见,所有透明都不会显示。
UIImage *moonImage = [UIImage imageNamed:@"mask.png"];
CALayer *maskLayer = [CALayer layer];
[maskLayer setContents:(id)moonImage.CGImage];
[maskLayer setFrame:CGRectMake(0.0f, 0.0f, moonImage.size.width, moonImage.size.height)];
UIImageView *yourBackgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
// Keep your image view in tact here, just add:
[yourBackgroundImageView.layer setMask:maskLayer];