具有逐渐淡出边框的圆形UIView

4
我已经成功制作了一个具有光束渐变色的圆形,就像这样:

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添加到Storyboard并将其类设置为CircleView时,它的宽度=高度。
然而,我想把[UIColor yellowColor]变成[UIColor clearColor],这样看起来就像红色淡出去了,也就是外面透明的。
我发现将[UIColor yellowColor]更改为[UIColor clearColor]后,外部变成了黑色,如下图所示:

Circle with clear outer gradient

如何使红色颜色以圆形方式逐渐消失 - 因为将[UIColor yellowColor]设置为[UIColor clearColor]显然不起作用?
1个回答

0
在HTML术语中,+[UIColor clearColor]实际上是带有0.0 alpha的#000000。换句话说,名为clearUIColor是透明黑色。
在大多数情况下,当您使用此颜色时,这很好,因为它是完全透明的。但是,在创建两种颜色之间的渐变时,它可能会产生您在此处看到的 drastical 效果。
您可能想要使用-[UIColor withAlphaComponent:]方法,例如:
UIColor *transparentRed = [[UIColor redColor] colorWithAlphaComponent:0.0];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接