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

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?

MegaManX
  • 8,766
  • 12
  • 51
  • 83

1 Answers1

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

Setting this argument to NO solves my problem.

MegaManX
  • 8,766
  • 12
  • 51
  • 83
  • 1
    In case you're wondering, that argument is the `opaque` value: https://developer.apple.com/reference/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc – Senseful Apr 04 '17 at 19:15
  • 2
    All this did is remove the transparent part of my drawing (the rounded corners of the buttons) and ended up filling the background with the same color as the button, essentially making it a squared button which isn't what I want. – Hedylove Dec 30 '18 at 00:51