黑色到白色的径向渐变给出了整个黑屏

时间:2017-02-17 01:10:17

标签: ios objective-c core-graphics radial-gradients cggradientref

使用Core Graphics创建黑色到白色的径向渐变应该非常简单,但即使经过多次尝试,我也无法确定我出错的地方。

我想要这样的事情: enter image description here

这是我的代码:

CGFloat radius = shapeRect.size.width/2.0;
CGPoint center = CGPointMake(shapeRect.origin.x+shapeRect.size.width/2, shapeRect.origin.y+shapeRect.size.height/2);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(NULL, shapeRect.size.width, shapeRect.size.height, 8, shapeRect.size.width*4, colorSpace, kCGImageAlphaNone);
CGFloat components[] = {0.0,   1.0};
CGFloat locations[] = {0.0, 1.0};
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, 0);

CGImageRef img = CGBitmapContextCreateImage(context);
[maskedView setImage:[UIImage imageWithCGImage:img]];

CGGradientRelease(gradient);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

ShapeRect这里有self.view界限。

我得到一个整个黑屏,没有渐变作为输出。 我正在使用iPhone 7模拟器。

您的建议可以节省我的一天

谢谢。

1 个答案:

答案 0 :(得分:0)

请检查此代码段。您可以更改componentslocations值以获得所需内容并了解绘图的工作原理。请参阅CGGradientCreateWithColorComponents description

#import "TestView.h"

@implementation TestView {
    CGGradientRef _gradient;
}

-(void)drawRect:(CGRect)rect
{
    CGFloat radius = self.frame.size.width / 2.0;
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGGradientRef gradient = [self createGradient];
    CGContextDrawRadialGradient(context, gradient, center, 10, center, radius, kCGGradientDrawsBeforeStartLocation);
}

-(CGGradientRef)createGradient
{
    if (!_gradient) {
        CGFloat components[] = { 0.0, 1.0, 0.5, 0.5, 1.0, 0.3 };
        CGFloat locations[] = { 0.0, 0.6, 1.0 };
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
        _gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 3);
        CGColorSpaceRelease(colorSpace);
    }
    return _gradient;
}

- (void)layoutSubviews
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.layer.borderWidth = 1.;
}


@end

结果:

enter image description here