CGContextDrawRadialGradient For Non-Circular Glow

做~自己de王妃 提交于 2020-01-05 10:19:56

问题


I'm able to use CGContextDrawRadialGradient to make a sphere that does an alpha fade to UIColor.clearColor and it works.

However, I'm trying to do this type of thing:

While placing some strategic spheres around makes for an interesting effect (similar to LED backlights in strategic places), I would love to get a true glow. How can I draw a glow around a rounded rectangle in drawRect?


回答1:


You can create a glow effect around any path using CGContextSetShadowWithColor, but you don't get precise control over the appearance. In particular, the default shadow is fairly light:

And the only way I know of to make it darker is to draw it again over itself:

Not optimal, but it approximates what you want pretty well.

Those images were generated by the following drawRect:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGMutablePathRef path = CGPathCreateMutable();

    int padding = 20;
    CGPathMoveToPoint(path, NULL, padding, padding);
    CGPathAddLineToPoint(path, NULL, rect.size.width - padding, rect.size.height / 2);
    CGPathAddLineToPoint(path, NULL, padding, rect.size.height - padding);

    CGContextSetShadowWithColor(context, CGSizeZero, 20, UIColor.redColor.CGColor);
    CGContextSetFillColorWithColor(context, UIColor.blueColor.CGColor);

    CGContextAddPath(context, path);
    CGContextFillPath(context);
    // CGContextAddPath(context, path);
    // CGContextFillPath(context);

    CGPathRelease(path);
}

One thing to bear in mind is that rendering fuzzy shadows is fairly expensive, which may or may not be a problem depending on how often your views are redrawn. If the shadows don't need to animate, consider rendering them to a UIImage once and just displaying the result in a UIImageView.



来源:https://stackoverflow.com/questions/10080405/cgcontextdrawradialgradient-for-non-circular-glow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!