CGContextDrawRadialGradient用于非圆形发光 [英] CGContextDrawRadialGradient For Non-Circular Glow
问题描述
我可以使用 CGContextDrawRadialGradient
制作一个球体,该球体的alpha渐变为 UIColor.clearColor
,
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:
同时在周围放置一些战略性区域有趣的效果(类似于战略性场所的LED背光),我很想获得真正的发光。 如何在 drawRect
的圆角矩形周围绘制辉光?
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
?
推荐答案
您可以使用 CGContextSetShadowWithColor
在任何路径周围创建发光效果,但是您无法精确控制外观。特别是,默认阴影相当浅:
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:
不是最佳的
这些图像是由以下 drawRect
生成的:
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);
}
要记住的一件事是渲染模糊阴影相当昂贵,取决于是否多久重新绘制一次视图,可能是问题,也可能不是问题。如果阴影不需要设置动画,请考虑将其渲染到 UIImage
一次,然后在 UIImageView
。
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
.
这篇关于CGContextDrawRadialGradient用于非圆形发光的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!