iOS Swift 如何绘制带模糊背景的自定义曲线视图
iOS Swift 带模糊背景的曲线视图实现方案
需求参考效果

现有代码问题排查
- 连续两次调用
path.move(to:)方法,第一次设置的起点被第二次覆盖,路径初始坐标错误 - 右侧圆弧中心点y值写死为100,没有适配控件自身高度,坐标计算逻辑不符合预期
- 在
draw(_ rect:)生命周期方法中反复插入CAShapeLayer,会导致图层重复叠加,引发显示异常和内存冗余 - 阴影设置逻辑错误:未指定
shadowPath的前提下,系统无法自动计算带自定义路径图层的阴影,导致阴影不显示 - 缺少模糊效果相关实现,仅配置了白色填充的曲线图层,无法实现需求中的模糊背景效果
修正后可运行代码
@IBDesignable class CurvedHeaderView: UIView { @IBInspectable var curveHeight: CGFloat = 50.0 @IBInspectable var blurStyle: UIBlurEffect.Style = .light private let curvedLayer = CAShapeLayer() private let blurEffectView = UIVisualEffectView(effect: nil) private let shadowLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } private func setupView() { backgroundColor = .clear // 配置阴影层 shadowLayer.shadowColor = UIColor.black.cgColor shadowLayer.shadowRadius = 10.0 shadowLayer.shadowOpacity = 0.7 shadowLayer.fillColor = UIColor.clear.cgColor layer.insertSublayer(shadowLayer, at: 0) // 配置模糊层 blurEffectView.effect = UIBlurEffect(style: blurStyle) blurEffectView.translatesAutoresizingMaskIntoConstraints = false insertSubview(blurEffectView, at: 0) NSLayoutConstraint.activate([ blurEffectView.topAnchor.constraint(equalTo: topAnchor), blurEffectView.leadingAnchor.constraint(equalTo: leadingAnchor), blurEffectView.trailingAnchor.constraint(equalTo: trailingAnchor), blurEffectView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } override func layoutSubviews() { super.layoutSubviews() let rect = bounds // 构建正确的曲线路径 let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: rect.height)) path.addLine(to: CGPoint(x: rect.width, y: rect.height)) // 右侧圆弧 path.addArc(withCenter: CGPoint(x: rect.width - curveHeight, y: rect.height - curveHeight), radius: curveHeight, startAngle: 0, endAngle: 1.5 * .pi, clockwise: false) path.addLine(to: CGPoint(x: curveHeight, y: 0)) // 左侧圆弧 path.addArc(withCenter: CGPoint(x: curveHeight, y: curveHeight), radius: curveHeight, startAngle: 1.5 * .pi, endAngle: .pi, clockwise: false) path.close() curvedLayer.path = path.cgPath blurEffectView.layer.mask = curvedLayer // 给阴影层设置路径 shadowLayer.path = path.cgPath shadowLayer.frame = rect } }
实现说明
- 图层初始化统一放在
setupView方法中,避免反复创建和插入图层 - 路径构建逻辑调整为适配控件自身高度,曲线坐标会随控件尺寸变化自动适配
- 模糊效果通过
UIVisualEffectView实现,用曲线路径作为模糊层的mask,保证模糊效果只在曲线范围内展示 - 单独新增阴影层专门负责渲染阴影,避免mask对阴影效果产生裁剪影响
内容的提问来源于stack exchange,提问作者Manikandan S
相关产品推荐
相关产品推荐

