1. 程式人生 > 實用技巧 >繪製圓形發散漸變

繪製圓形發散漸變

- (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