ios - 非圆形发光的 CGContextDrawRadialGradient

标签 ios core-graphics

我可以使用 CGContextDrawRadialGradient 制作一个球体,它可以将 alpha 淡化到 UIColor.clearColor 并且它可以工作。

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

enter image description here

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

最佳答案

您可以使用 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);
}

要记住的一件事是渲染模糊阴影相当昂贵,这可能会或可能不会成为问题,具体取决于您的 View 重绘的频率。如果阴影不需要动画,请考虑将它们渲染到 UIImage 一次,然后只在 UIImageView 中显示结果。

关于ios - 非圆形发光的 CGContextDrawRadialGradient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10080405/

相关文章:

iOS - 在选择器 View 中访问文本变量以在通知声音名称中使用

ios - 重新启动 Xcode 加载 Xcode 片段

ios - 如何在闭包中访问类的变量?

ios - 如何在 ios 的 swift 语言中为具有其他类型输入的变量设置 setter?

ios - 检测 CAShapeLayer 列表中的长按

iphone - 平滑 Core Graphics 中的圆形笔划

iOS错误: Thread 1:EXC_BAD_ACCESS(code=1,地址=0x726f635f)?

iphone - CGColorRef 导致崩溃

ios - 创建可点击的 CGPath

iphone - 学习在线类(class),掌握职场技能