Iphone How to make context background transparent?

2019-01-25 03:48发布

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];

This is the code i have written so far. First i make layer with moon image. Then i add second layer with custom drawing that should cover part of the moon. However contextRef renders its background black, so when i put second layer, first is invisible. Is there any way i can solve this? Better yet is there a better way to make custom drawing programatically and add it to layer?

1条回答
我想做一个坏孩纸
2楼-- · 2019-01-25 03:56
UIGraphicsBeginImageContextWithOptions(CGSizeMake(400, 400), NO, 1);

Setting this argument to NO solves my problem.

查看更多
登录 后发表回答