径向渐变中颜色无法正常工作

时间:2013-09-02 04:43:09

标签: ios core-graphics

我正在使用径向渐变绘制圆形。它工作正常但是当我尝试在该圆圈中填充黑白颜色时,它无法正常工作。当我运行我的黑白颜色的应用程序时,它采取绿色黑色和黄色,白色。这是我的代码:`

CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
CGContextSetLineWidth(contextRef, borderWidth);
CGContextSetFillColorWithColor(contextRef, borderColor.CGColor);
//draw border
CGContextFillEllipseInRect(contextRef, CGRectMake(self.bounds.size.width/2 - (radius), self.bounds.size.height/2 - (radius), 2*radius, 2*radius));
//components from gradientColor1 and gradientColor2
CGFloat red1;
CGFloat green1;
CGFloat blue1;
{
    const CGFloat *components = CGColorGetComponents(gradientColor1.CGColor);
    red1 = components[0];
    green1 = components[1];
    blue1 = components[2];
}
CGFloat red2;
CGFloat green2;
CGFloat blue2;
{
    const CGFloat *components = CGColorGetComponents(gradientColor2.CGColor);
    red2 = components[0];
    green2 = components[1];
    blue2 = components[2];
}
//radial gradient color
CGGradientRef gradient;
CGColorSpaceRef colorSpace;
CGFloat locations[] = {0.0,1.0};
CGFloat components[] = { red2,green2,blue2,1.0,red1,green1,blue1,1.0  };
colorSpace = CGColorSpaceCreateDeviceRGB();
gradient = CGGradientCreateWithColorComponents(colorSpace,components,locations,
                                               sizeof(locations)/sizeof(CGFloat));
CGPoint start = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2 ), end = CGPointMake(self.bounds.size.width/2 , self.bounds.size.height/2);
CGFloat startRadius = 0.0, endRadius = radius - borderWidth;
CGContextDrawRadialGradient(contextRef,gradient,start,startRadius,end,endRadius,0);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);

这里gradientColor1是白色,gradientColor2是黑色。请帮帮我。谢谢。请参考图片:

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试使用

NSArray *colors = [NSArray arrayWithObjects:
                                              (id)[UIColor colorWithWhite: 1.0 alpha: 1.0].CGColor,
                                              (id)[UIColor colorWithWhite: 0.0 alpha: 1.0].CGColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);