19
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呈現其背景爲黑色,所以當我把第二層,第一層是不可見的。有什麼辦法可以解決這個問題嗎?更好的是有沒有更好的方式來編程自定義繪圖並將其添加到圖層?iphone如何使上下文背景透明?
如果你想知道,那個參數是'不透明'的值:https://developer.apple.com/reference/uikit/1623912-uigraphicsbeginimagecontextwitho?language=objc – Senseful 2017-04-04 19:15:28