您的位置:首页 > 移动开发 > IOS开发

layer绘制渐变色

2015-12-11 19:17 441 查看
layer绘制渐变色
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    NSArray *colors = [NSArray arrayWithObjects:HEXCOLOR(0x769DC5),HEXCOLOR(0x4F5B9B), nil];
    [self drawGradientColor:context rect:rect options:kCGGradientDrawsAfterEndLocation colors:colors];
    CGContextStrokePath(context);// 描线,即绘制形状
    CGContextFillPath(context);// 填充形状内的颜色
}

/**
 * 绘制背景色渐变的矩形,p_colors渐变颜色设置,集合中存储UIColor对象(创建Color时一定用三原色来创建)
 **/
- (void)drawGradientColor:(CGContextRef)pContext
                     rect:(CGRect)pClipRect
                  options:(CGGradientDrawingOptions)pOptions
                   colors:(NSArray *)pColors {
    CGContextSaveGState(pContext);// 保持住现在的context
    CGContextClipToRect(pContext, pClipRect);// 截取对应的context
    int colorCount = (int)pColors.count;
    int numOfComponents = 4;
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colorComponents[colorCount * numOfComponents];
    
    for (int i = 0; i < colorCount; i++) {
        UIColor *color = pColors[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 = pClipRect.origin;
    CGPoint endPoint = CGPointMake(CGRectGetMinX(pClipRect), CGRectGetMaxY(pClipRect));
    CGContextDrawLinearGradient(pContext, gradient, startPoint, endPoint, pOptions);
    CGGradientRelease(gradient);
    CGContextRestoreGState(pContext);// 恢复到之前的context
}
 //加阴影
 _bgView.layer.shadowColor = [UIColor
grayColor].CGColor;//shadowColor阴影颜色
 _bgView.layer.shadowOffset =
CGSizeMake(2,1);//shadowOffset阴影偏移,x向右偏移4,y向下偏移4,默认(0,
-3),这个跟shadowRadius配合使用
 _bgView.layer.shadowOpacity =
0.5;//阴影透明度,默认0
 _bgView.layer.shadowRadius =
3;//阴影半径,默认3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS