ios - Iphone 如何使上下文背景透明?

标签 ios iphone drawing calayer cgcontext

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 将其背景呈现为黑色,因此当我放置第二层时,第一层是不可见的。有什么办法可以解决这个问题吗?更好的是,是否有更好的方法以编程方式制作自定义绘图并将其添加到图层?

最佳答案

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

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

关于ios - Iphone 如何使上下文背景透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8506754/

相关文章:

ios - Tidwall/安全互斥死锁

iphone - ios应用程序的配置文件

python - 画一条几乎直线

ios - 归档 iOS 应用程序 swift 时出错

ios - 扫描成功后如何关闭二维码扫描器 - Swift 4

ios - 如何将我的标签栏图标连接到我的屏幕?

ios - 如何让 UIAlert 按钮按下前进到下一个 Storyboard?

iphone - 识别上一个 UIView 的名称

android - 我的 paintview android 中的重做撤消操作问题

javascript - Canvas 路径到底是什么,ctx.closePath()有什么用?