iOS 绘制背景色渐变的矩形

迁移自开源中国

使用

CGContextRef context = UIGraphicsGetCurrentContext();
NSArray *colors = [NSArray arrayWithObjects:
                   [UIColor colorWithRed:225.0 / 255.0 green:225.0 / 255.0 blue:225.0 / 255.0 alpha:1.0],
                   [UIColor colorWithRed:168.0 / 255.0 green:168.0 / 255.0 blue:168.0 / 255.0 alpha:1.0],
                   nil];
[self drawGradientColor:context
                   rect:CGRectMake(rX, rY, rW, rH)
                options:kCGGradientDrawsAfterEndLocation
                 colors:colors];
CGContextStrokePath(context);// 描线,即绘制形状
CGContextFillPath(context);// 填充形状内的颜色

方法

/**
 * 绘制背景色渐变的矩形,p_colors渐变颜色设置,集合中存储UIColor对象(创建Color时一定用三原色来创建)
 **/
- (void)drawGradientColor:(CGContextRef)p_context
                     rect:(CGRect)p_clipRect
                  options:(CGGradientDrawingOptions)p_options
                   colors:(NSArray *)p_colors {
    CGContextSaveGState(p_context);// 保持住现在的context
    CGContextClipToRect(p_context, p_clipRect);// 截取对应的context
    int colorCount = p_colors.count;
    int numOfComponents = 4;
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colorComponents[colorCount * numOfComponents];
    for (int i = 0; i < colorCount; i++) {
        UIColor *color = p_colors[i];
        CGColorRef temcolorRef = color.CGColor;
        const CGFloat *components = CGColorGetComponents(temcolorRef);
        for (int j = 0; j < numOfComponents; ++j) {
            colorComponents[i * numOfComponents + j] = components[j];
        }
    }
    CGGradientRef gradient =  CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, colorCount);
    CGColorSpaceRelease(rgb);
    CGPoint startPoint = p_clipRect.origin;
    CGPoint endPoint = CGPointMake(CGRectGetMinX(p_clipRect), CGRectGetMaxY(p_clipRect));
    CGContextDrawLinearGradient(p_context, gradient, startPoint, endPoint, p_options);
    CGGradientRelease(gradient);
    CGContextRestoreGState(p_context);// 恢复到之前的context
}

还可以这样

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(rX, rY, rW, rH);
gradient.colors = [NSArray arrayWithObjects:
                       (id)[UIColor blackColor].CGColor,
                       (id)[UIColor grayColor].CGColor,
                       (id)[UIColor blackColor].CGColor,
                        nil];
[self.view.layer insertSublayer:gradient atIndex:0];

记得要#import

此文的完成用到了四位老师的文章,在此表示感谢。
http://www.cnblogs.com/pengyingh/articles/2378840.html
http://www.dapps.net/dev/code/ios-dev-cgcontext-tips.html
http://www.cnblogs.com/smileEvday/archive/2012/06/05/UIColor_CIColor_CGColor.html
http://blog.csdn.net/reylen/article/details/8622932

你可能感兴趣的:(iOS 绘制背景色渐变的矩形)