ios實現顏色漸變的幾種方法

 

demo地址:https://github.com/xiaochaofeiyu/YSCAnimation
有用的話求個star,歡迎建議討論。git

1. CAGradientLayer實現漸變

CAGradientLayer是CALayer的一個特殊子類,用於生成顏色漸變的圖層,使用較爲方便,下面介紹下它的相關屬性:github

  1. colors 漸變的顏色
  2. locations 漸變顏色的分割點
  3. startPoint&endPoint 顏色漸變的方向,範圍在(0,0)與(1.0,1.0)之間,如(0,0)(1.0,0)表明水平方向漸變,(0,0)(0,1.0)表明豎直方向漸變
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor yellowColor].CGColor, (__bridge id)[UIColor blueColor].CGColor];
    gradientLayer.locations = @[@0.3, @0.5, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 0);
    gradientLayer.frame = CGRectMake(0, 100, 300, 100);
    [self.view.layer addSublayer:gradientLayer];

CAGradientLayer實現漸變標間簡單直觀,但存在必定的侷限性,好比沒法自定義整個漸變區域的形狀,如環形、曲線形的漸變。函數

2. Core Graphics相關方法實現漸變

iOS Core Graphics中有兩個方法用於繪製漸變顏色,CGContextDrawLinearGradient能夠用於生成線性漸變,CGContextDrawRadialGradient用於生成圓半徑方向顏色漸變。函數能夠自定義path,不管是什麼形狀均可以,原理都是用來作Clip,因此須要在CGContextClip函數前調用CGContextAddPath函數把CGPathRef加入到Context中。
另一個須要注意的地方是漸變的方向,方向是由兩個點控制的,點的單位就是座標。所以須要正確從CGPathRef中找到正確的點,方法固然有不少種看具體實現,本例中,我就是簡單得經過調用CGPathGetBoundingBox函數,返回CGPathRef的矩形區域,而後根據這個矩形取兩個點,讀者能夠根據自行需求修改具體代碼。spa

1-> 線性漸變code

- (void)drawLinearGradient:(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 startPoint = CGPointMake(CGRectGetMinX(pathRect), CGRectGetMidY(pathRect));
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(pathRect), CGRectGetMidY(pathRect));
    
    CGContextSaveGState(context);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 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));
    CGPathCloseSubpath(path);
    
    //繪製漸變
    [self drawLinearGradient: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];
}

2-> 圓半徑方向漸變對象

- (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];
}

3. 以CAShapeLayer做爲layer的mask屬性

CALayer的mask屬性能夠做爲遮罩讓layer顯示mask遮住(非透明)的部分;CAShapeLayer爲CALayer的子類,經過path屬性能夠生成不一樣的形狀,將CAShapeLayer對象用做layer的mask屬性的話,就能夠生成不一樣形狀的圖層。故生成顏色漸變有如下幾個步驟:圖片

  1. 生成一個imageView(也能夠爲layer),image的屬性爲顏色漸變的圖片
  2. 生成一個CAShapeLayer對象,根據path屬性指定所需的形狀
  3. 將CAShapeLayer對象賦值給imageView的mask屬性
- (void)viewDidLoad
{
    [super viewDidLoad];
        
    [self.view addSubview:self.firstCircle];
    _firstCircle.frame = CGRectMake(0, 0, 200, 200);
    _firstCircle.center = CGPointMake(CGRectGetWidth(self.view.bounds) / 2.0, CGRectGetHeight(self.view.bounds) / 2.0);
    CGFloat firsCircleWidth = 5;
    self.firstCircleShapeLayer = [self generateShapeLayerWithLineWidth:firsCircleWidth];
    _firstCircleShapeLayer.path = [self generateBezierPathWithCenter:CGPointMake(100, 100) radius:100].CGPath;
    _firstCircle.layer.mask = _firstCircleShapeLayer;
} 

- (CAShapeLayer *)generateShapeLayerWithLineWidth:(CGFloat)lineWidth
{
    CAShapeLayer *waveline = [CAShapeLayer layer];
    waveline.lineCap = kCALineCapButt;
    waveline.lineJoin = kCALineJoinRound;
    waveline.strokeColor = [UIColor redColor].CGColor;
    waveline.fillColor = [[UIColor clearColor] CGColor];
    waveline.lineWidth = lineWidth;
    waveline.backgroundColor = [UIColor clearColor].CGColor;
    
    return waveline;
}

- (UIBezierPath *)generateBezierPathWithCenter:(CGPoint)center radius:(CGFloat)radius
{
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0 endAngle:2*M_PI clockwise:NO];
    
    return circlePath;
}

- (UIImageView *)firstCircle
{
    if (!_firstCircle) {
        self.firstCircle = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"circleBackground"]];
        _firstCircle.layer.masksToBounds = YES;
        _firstCircle.alpha = 1.0;
    }
    
    return _firstCircle;
}



做者:小超飛魚
連接:http://www.jianshu.com/p/3e0e25fd9b85
來源:簡書
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。ip

相關文章
相關標籤/搜索