gpt4 book ai didi

iphone - 如何在drawRect中用渐变填充路径:?

转载 作者:行者123 更新时间:2023-12-03 18:12:48 26 4
gpt4 key购买 nike

用纯色填充路径非常简单:

CGPoint aPoint;
for (id pointValue in points)
{
aPoint = [pointValue CGPointValue];
CGContextAddLineToPoint(context, aPoint.x, aPoint.y);
}
[[UIColor redColor] setFill];
[[UIColor blackColor] setStroke];
CGContextDrawPath(context, kCGPathFillStroke);

我想绘制渐变而不是纯红色,但我遇到了麻烦。我已经尝试过问题/答案中列出的代码:Gradients on UIView and UILabels On iPhone

这是:

CAGradientLayer *gradient = [CAGradientLayer layer];
[gradient setFrame:rect];
[gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor],
(id)[[UIColor whiteColor] CGColor], nil]];
[[self layer] setMasksToBounds:YES];

[[self layer] insertSublayer:gradient atIndex:0];

但是,这会用渐变绘制整个 View ,覆盖我原来的路径。

最佳答案

我会剪辑到您想要填充的路径,并使用CGContextDrawLinearGradient。下面以一个drawRect的简单实现为例:

- (void) drawRect:(CGRect)rect
{
// Create a gradient from white to red
CGFloat colors [] = {
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 0.0, 1.0
};

CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);

CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;

CGContextRestoreGState(context);

CGContextAddEllipseInRect(context, rect);
CGContextDrawPath(context, kCGPathStroke);
}

关于iphone - 如何在drawRect中用渐变填充路径:?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2985359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com