【发布时间】:2012-04-06 14:16:36
【问题描述】:
在CAShapeLayer 上,我画了一个封闭的UIBezierPath。我可以通过设置fillColor 来填充这个形状,但是我想用渐变来填充这个形状。如何设置CAGradientLayer使其剪辑到贝塞尔路径所勾勒的形状?
【问题讨论】:
标签: ios uibezierpath cagradientlayer
在CAShapeLayer 上,我画了一个封闭的UIBezierPath。我可以通过设置fillColor 来填充这个形状,但是我想用渐变来填充这个形状。如何设置CAGradientLayer使其剪辑到贝塞尔路径所勾勒的形状?
【问题讨论】:
标签: ios uibezierpath cagradientlayer
草稿示例如下:
...
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);
...
【讨论】:
CGContextDrawLinearGradient之前添加了以下内容:CGContextAddPath(context, roundedRectanglePath.CGPath);CGContextClip(context);
你想要的是一个面具。 CAGradientlayer 有一个 -setMask 方法,可以像这样将其剪辑到形状的边界:
[gradientLayer setMask:shapeLayer];
【讨论】: