渐变 CGGradient

来源:互联网 发布:java细粒度数据级权限 编辑:程序博客网 时间:2024/05/21 20:23

颜色渐变指从一种颜色向另一种颜色的过渡,颜色渐变分为两种:线性渐变和径向渐变

Quartz提供了CGGradient类和CGShading类以支持颜色渐变。

    CGGradientRef myGradient;    CGColorSpaceRef myColorspace;    size_t num_locations = 2;    CGFloat locations[2] = {0.0, 1.0};    CGFloat components[8] = {1.0, 0.5, 0.4, 1.0,            //开始颜色(RGB)                                                0.8, 0.8, 0.3, 1.0};           //终止颜色(RGB)    myColorspace = CGColorSpaceCreateDeviceRGB();    /*     *第一个参数:颜色空间     *第二个参数:CGFloat数组,指定渐变的开始颜色,终止颜色,以及过度色(如果有的话)     *第三个参数:指定每个颜色在渐变色中的位置,值介于0.0-1.0之间     *                      0.0表示最开始的位置,1.0表示渐变结束的位置     *第四个参数:渐变中使用的颜色数     */    myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations);    CGPoint myStartPoint, myEndPoint;    myStartPoint.x = 0.0;    myStartPoint.y = 0.0;    myEndPoint.x = _imgView.frame.size.width;    myEndPoint.y = _imgView.frame.size.height;        UIGraphicsBeginImageContext(_imgView.frame.size);    CGContextRef ctx = UIGraphicsGetCurrentContext();    CGContextDrawLinearGradient(ctx, myGradient, myStartPoint, myEndPoint, 0);//绘制颜色渐变    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();    _imgView.image = image;    UIGraphicsEndImageContext();


2.径向渐变
    CGContextRef context = UIGraphicsGetCurrentContext();    UIGraphicsPushContext(context);    size_t gradLocationNum = 2;    CGFloat gradLocation[2] = {0.0f, 1.0f};    CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.9f};    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocation, gradLocationNum);    //渐变的中心    CGPoint gradCenter = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);    //渐变的半径    float gradRadius = MIN(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));    //Gradient Draw    CGContextDrawRadialGradient(context, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);    CGGradientRelease(gradient);    UIGraphicsPopContext();



0 0