iPhone 如何使上下文背景透明?

22
CALayer *sublayer = [CALayer layer];
/*sublayer.backgroundColor = [UIColor blueColor].CGColor;
sublayer.shadowOffset = CGSizeMake(0, 3);
sublayer.shadowRadius = 5.0;
sublayer.shadowColor = [UIColor blackColor].CGColor;
sublayer.shadowOpacity = 0.8;*/
sublayer.frame = CGRectMake(30, 100, 256, 256);
sublayer.contents = (id)[[UIImage imageNamed:@"moon.png"] CGImage];
[self.view.layer addSublayer:sublayer];
//self.view.backgroundColor = [UIColor blackColor];

//add moon mask
UIGraphicsBeginImageContextWithOptions(CGSizeMake(400, 400), YES, 1);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextClearRect(contextRef, CGRectMake(0, 0, 400, 400));
CGContextSetRGBFillColor(contextRef, 1, 1, 1, 0.8);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 0, 0.5);
CGRect ellipse = CGRectMake(50, 50, 128, 128);
CGContextAddEllipseInRect(contextRef, ellipse);
CGContextFillEllipseInRect(contextRef, ellipse);

CALayer* sublayer2 = [CALayer layer];
sublayer2.frame = CGRectMake(30, 100, 256, 256);
sublayer2.backgroundColor = [UIColor clearColor].CGColor;
sublayer2.contents = (id)[UIGraphicsGetImageFromCurrentImageContext() CGImage];
[self.view.layer addSublayer:sublayer2];

这是我到目前为止编写的代码。首先,我用月亮图像创建了一层。然后我添加了第二个带有自定义绘图的图层,应该覆盖部分月亮。但是,contextRef渲染其背景为黑色,因此当我放置第二个图层时,第一个图层会变得不可见。是否有任何方法可以解决这个问题?更好的方法是以编程方式制作自定义绘图并将其添加到图层中吗?

1个回答

62
UIGraphicsBeginImageContextWithOptions(CGSizeMake(400, 400), NO, 1);

将此参数设置为NO解决了我的问题。


1
如果你想知道,那个参数是“opaque”值:https://developer.apple.com/reference/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc - Senseful
2
这只是移除了我的绘图中透明的部分(按钮的圆角),最终将背景填充了与按钮相同的颜色,从而使其成为一个方形的按钮,这并不是我想要的。 - Hedylove

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接