iOS UIView 为什么绘制的三角形区域未能填充颜色渐变


// YSHHypnosisView.m // Hypnosister #import "YSHHypnosisView.h" @implementation YSHHypnosisView // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code CGRect bounds = self.bounds; CGPoint center; center.x = bounds.origin.x + bounds.size.width / 2.0; center.y = bounds.origin.y + bounds.size.height / 2.0; float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0; UIBezierPath *path = [[UIBezierPath alloc] init]; for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) { [path moveToPoint:CGPointMake(center.x + currentRadius, center.y)]; [path addArcWithCenter:center radius:currentRadius startAngle:0.0 endAngle:M_PI * 2.0 clockwise:YES]; } path.lineWidth = 10; [[UIColor lightGrayColor] setStroke]; [path stroke]; // start... CGContextRef currentContext = UIGraphicsGetCurrentContext(); // 2、绘制渐变 // 2.1绘制三角形 UIBezierPath *myPath = [UIBezierPath bezierPath]; [myPath moveToPoint:CGPointMake(160, 142)]; [myPath addLineToPoint:CGPointMake(260, 446)]; [myPath moveToPoint:CGPointMake(260, 446)]; [myPath addLineToPoint:CGPointMake(60, 446)]; [myPath moveToPoint:CGPointMake(60, 446)]; [myPath addLineToPoint:CGPointMake(160, 142)]; [myPath stroke]; CGContextSaveGState(currentContext); [myPath addClip]; // 为myPath填充渐变 // 为什么三角形没有填充渐变? CGFloat locations[2] = {0.0, 1.0}; CGFloat components[8] = {1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0}; // yellow->red CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, 2); CGPoint startPoint = CGPointMake(160, 142); CGPoint endPoint = CGPointMake(160, 446); CGContextDrawLinearGradient(currentContext, gradient, startPoint, endPoint, 0); CGGradientRelease(gradient); CGColorSpaceRelease(colorspace); CGContextRestoreGState(currentContext); // 1、绘制阴影 CGContextSaveGState(currentContext); CGContextSetShadow(currentContext, CGSizeMake(4, 7), 2); UIImage *logoImage = [UIImage imageNamed:@"logo.png"]; [logoImage drawInRect:CGRectMake(80, 142, self.window.frame.size.width / 2.0, self.window.frame.size.height / 2.0)]; CGContextRestoreGState(currentContext); // end... } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; } return self; } @end

图片描述

阅读 7.2k
1 个回答

你的贝塞尔曲线设置是错误的。
moveToPoint的作用你没有理解,可以再看一下API。
只要把除了第一个意外的moveToPoint删掉,就可以了。

UIBezierPath *myPath = [UIBezierPath bezierPath];
[myPath moveToPoint:CGPointMake(160, 142)];
[myPath addLineToPoint:CGPointMake(260, 446)];
[myPath addLineToPoint:CGPointMake(60, 446)];
[myPath addLineToPoint:CGPointMake(160, 142)];

就对了

图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题