问题
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