圆形UIView,边界逐渐淡出

时间:2017-01-26 15:27:53

标签: ios objective-c core-graphics

我设法使用径向渐变颜色制作圆圈,如下所示:

Circle with yellow outer gradient

@interface CircleView : UIView
@end

@implementation CircleView

- (void)drawRect:(CGRect)rect {

    const CGContextRef context = UIGraphicsGetCurrentContext();

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    NSArray *gradientColors = [NSArray arrayWithObjects:
                           (id)[UIColor redColor].CGColor,
                           (id)[UIColor yellowColor].CGColor, nil];
    CGFloat gradientLocations[] = {0.0, 0.5};
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)gradientColors, gradientLocations);

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithOvalInRect:rect];
    CGContextSaveGState(context);
    [roundedRectanglePath fill];
    [roundedRectanglePath addClip];
    CGPoint gradCenter= CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    CGContextDrawRadialGradient (context, gradient, gradCenter, 0, gradCenter, rect.size.width, kCGGradientDrawsBeforeStartLocation);
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
}
@end

确保在将UIView添加到故事板并将其类设置为CircleView时,它的宽度=高度。

但是我想将[UIColor yellowColor]变成[UIColor clearColor]所以看起来红色淡出,即外面是透明的。

我发现通过将[UIColor yellowColor]更改为[UIColor clearColor],外部变为黑色,如:

Circle with clear outer gradient

如何使红色逐渐淡出 - 因为将[UIColor yellowColor]设置为[UIColor clearColor]显然不起作用?

1 个答案:

答案 0 :(得分:0)

在HTML术语中,+[UIColor clearColor]实际上是#000000,其alpha值为0.0。换句话说,名为UIColor的{​​{1}}是透明的黑色。

在大多数使用此颜色的情况下都可以,因为它完全透明。但是,当您在两种颜色之间创建渐变时,它会产生您在此处看到的剧烈效果。

您可能想要使用clear方法,例如

-[UIColor withAlphaComponent:]
相关问题