CGContextDrawRadialGradient用于非圆形发光

时间:2012-04-09 21:58:28

标签: ios core-graphics

我可以使用CGContextDrawRadialGradient创建一个对UIColor.clearColor执行alpha淡化的球体,并且它可以正常工作。

但是,我正在尝试做这类事情:

enter image description here

虽然放置一些战略领域会产生有趣的效果(类似于战略场所的LED背光),但我希望得到真正的光芒。 如何在drawRect中的圆角矩形周围绘制光晕?

1 个答案:

答案 0 :(得分:2)

您可以使用CGContextSetShadowWithColor在任何路径周围创建发光效果,但无法精确控制外观。特别是,默认阴影相当轻:

the default shadow

我所知道的唯一让它变暗的方法就是再次画出它:

enter image description here

不是最佳的,但它很接近你想要的东西。

这些图片是由以下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中显示结果。