You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CAShapeLayer结合UIBezierPath绘制线条时如何仅为线条添加阴影

解决方案

出现阴影仅显示在半圆弧外侧的核心原因是:CAShapeLayer默认会将传入的path作为填充路径计算阴影边界,开放式的半圆路径会被系统自动补全两端连线形成闭合区域,阴影只会生成在该闭合区域外侧,不会匹配线条本身的轮廓。

你可以通过显式指定和描边线条轮廓完全匹配的shadowPath实现仅给线条本身加投影的效果,修改后的代码如下:

let bounds = UIScreen.main.bounds

let shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(x: 0, y: 0 , width: bounds.width, height: bounds.width)

shapeLayer.lineWidth = 5.0
shapeLayer.strokeColor = UIColor.red.cgColor
// 先设置填充色为透明,避免填充半圆内部区域
shapeLayer.fillColor = UIColor.clear.cgColor

let offset : CGFloat = 20
let arcCenter = shapeLayer.position
let radius = shapeLayer.bounds.size.width / 2.0 - offset
let startAngle = CGFloat(0.0)
let endAngle = CGFloat(1.0 * .pi)

let circlePath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)

// 核心修改:生成和线条描边轮廓完全匹配的阴影路径
let strokeShadowPath = circlePath.copy(
    strokingWithWidth: shapeLayer.lineWidth,
    lineCap: shapeLayer.lineCap,
    lineJoin: shapeLayer.lineJoin,
    miterLimit: shapeLayer.miterLimit
)
shapeLayer.shadowPath = strokeShadowPath.cgPath

shapeLayer.shadowOffset = CGSize(width: 0, height: 0)
shapeLayer.shadowColor = UIColor.red.cgColor
shapeLayer.shadowOpacity = 1.0
shapeLayer.shadowRadius = 25

shapeLayer.path = circlePath.cgPath

注意事项

  • 如果后续修改了线条的lineWidth、path、lineCap、lineJoin属性,需要同步更新shadowPath,避免阴影和线条错位
  • 该方案性能损耗极低,无需额外新增图层即可实现效果

内容的提问来源于stack exchange,提问作者kungfuslippers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:54:01