绘制圆形发散渐变

- (void)drawRadialGradient:(CGContextRef)context
  path:(CGPathRef)path
 startColor:(CGColorRef)startColor
  endColor:(CGColorRef)endColor
{
 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
 CGFloat locations[] = { 0.0, 1.0 };

 NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];

 CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);


 CGRect pathRect = CGPathGetBoundingBox(path);
 CGPoint center = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMidY(pathRect));
 CGFloat radius = MAX(pathRect.size.width / 2.0, pathRect.size.height / 2.0) * sqrt(2);

 CGContextSaveGState(context);
 CGContextAddPath(context, path);
 CGContextEOClip(context);

 CGContextDrawRadialGradient(context, gradient, center, 0, center, radius, 0);

 CGContextRestoreGState(context);

 CGGradientRelease(gradient);
 CGColorSpaceRelease(colorSpace);
}

- (void)viewDidLoad 
{
 [super viewDidLoad];
 // Do any additional setup after loading the view.

 //创建CGContextRef
 UIGraphicsBeginImageContext(self.view.bounds.size);
 CGContextRef gc = UIGraphicsGetCurrentContext();

 //创建CGMutablePathRef
 CGMutablePathRef path = CGPathCreateMutable();

 //绘制Path
 CGRect rect = CGRectMake(0, 100, 300, 200);
 CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
 CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMaxY(rect));
 CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMaxY(rect));
 CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetMinY(rect));
 CGPathCloseSubpath(path);

 //绘制渐变
 [self drawRadialGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];

 //注意释放CGMutablePathRef
 CGPathRelease(path);

 //从Context中获取图像,并显示在界面上
 UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
 [self.view addSubview:imgView];
}

 https://www.jb51.net/article/94356.htm

posted @ 2020-09-10 11:37  雨筱逸悠  阅读(187)  评论(0编辑  收藏  举报