绘制渐变色

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    //获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    
    //创建颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    //设置开始颜色和结束颜色
    UIColor *startColor = [UIColor blueColor];
    CGFloat *startC = (CGFloat *)CGColorGetComponents(startColor.CGColor);
    
    UIColor *endColor = [UIColor redColor];
    CGFloat *endC = (CGFloat *)CGColorGetComponents(endColor.CGColor);
    
    //获取颜色分量,存入数组
    CGFloat compoents[8] = {
        startC[0],
        startC[1],
        startC[2],
        startC[3],
        
        endC[0],
        endC[1],
        endC[2],
        endC[3],
    };
    
    //指定渐变开始的位置和结束的位置
    CGFloat colorIndices[2] = {
    
        0.0f,
        1.0f,
        
    };
    
    //gradient指向渐变对象
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, (const CGFloat *)&compoents, (const CGFloat *)colorIndices, 2);
    CGColorSpaceRelease(colorSpace);
 
    CGPoint startPoint,endPoint;
    startPoint = CGPointMake(0, 64);
    endPoint = CGPointMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    
                                                                        //扩展整个渐变之前的所有点和之后的所有点
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation|kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    
}