2012-04-06 124 views
8

CAShapeLayer上,我繪製了一個閉合的UIBezierPath。我可以通過設置fillColor來填充這個形狀,但是我想用漸變填充形狀。我如何設置CAGradientLayer,以便剪切到bezier路徑概述的形狀?在iOS上用漸變填充路徑

回答

5

你想要的是一個面具。 CAGradientlayer有-setMask方法,可以把它夾到你的形狀的界限,像這樣:

[gradientLayer setMask:shapeLayer];

19

一個例子草案將是以下幾點:

... 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = UIGraphicsGetCurrentContext(); 

UIColor *gradientColor = [UIColor colorWithRed:0.51 green:0.0 blue:0.49 alpha:1.0]; 

NSArray *gradientColors = [NSArray arrayWithObjects: 
          (id)[UIColor blueColor].CGColor, 
          (id)gradientColor.CGColor, 
          (id)[UIColor redColor].CGColor, nil]; 
CGFloat gradientLocations[] = {0, 0.5, 1}; 
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations); 

UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 10, 200, 200) cornerRadius:6]; 
CGContextSaveGState(context); 
[roundedRectanglePath fill]; 
[roundedRectanglePath addClip]; 
CGContextDrawLinearGradient(context, gradient, CGPointMake(10, 10), CGPointMake(210, 10), 0); 
CGColorSpaceRelease(colorSpace); 
CGGradientRelease(gradient); 

... 
+0

這是很好的,但你也應該釋放漸變和顏色空間。 – Sulthan 2013-03-17 13:48:52

+0

感謝,我忘了把它們 – WhiteTiger 2013-03-17 14:23:38

+0

,因爲原帖特色面具,我還增加了以下內容: 'CGContextAddPath(背景下,roundedRectanglePath.CGPath);'' CGContextClip(背景);' CGContextDrawLinearGradient'之前' – maggix 2013-07-04 10:32:43