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

iOS Swift实现带圆角衔接的箭头式徽章视图方案

Swift箭头视图实现圆角衔接的方案

你可以通过手动构建带圆角的UIBezierPath来实现线条衔接处的圆角效果,同时保留箭头尖端的尖锐形态。以下是修改后的完整代码:

class ArrowView: UIView {
    // 可自定义圆角半径,按需调整
    private let cornerRadius: CGFloat = 8
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        let bounds = self.bounds
        let arrowWidth = bounds.height / 2
        let path = UIBezierPath()
        
        // 左上角圆角
        path.move(to: CGPoint(x: cornerRadius, y: 0))
        path.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius),
                    radius: cornerRadius,
                    startAngle: .pi * 1.5,
                    endAngle: .pi,
                    clockwise: false)
        
        // 左下角圆角
        path.addLine(to: CGPoint(x: 0, y: bounds.height - cornerRadius))
        path.addArc(withCenter: CGPoint(x: cornerRadius, y: bounds.height - cornerRadius),
                    radius: cornerRadius,
                    startAngle: .pi,
                    endAngle: .pi * 0.5,
                    clockwise: false)
        
        // 箭头底部衔接处圆角
        path.addLine(to: CGPoint(x: bounds.width - arrowWidth, y: bounds.height - cornerRadius))
        path.addArc(withCenter: CGPoint(x: bounds.width - arrowWidth, y: bounds.height - cornerRadius),
                    radius: cornerRadius,
                    startAngle: .pi * 0.5,
                    endAngle: 0,
                    clockwise: false)
        
        // 箭头尖端(保持尖锐)
        path.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 2))
        
        // 箭头顶部衔接处圆角
        path.addLine(to: CGPoint(x: bounds.width - arrowWidth, y: cornerRadius))
        path.addArc(withCenter: CGPoint(x: bounds.width - arrowWidth, y: cornerRadius),
                    radius: cornerRadius,
                    startAngle: 0,
                    endAngle: .pi * 1.5,
                    clockwise: false)
        
        // 闭合路径
        path.close()

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.black.cgColor
        
        self.layer.addSublayer(shapeLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
        commonInit()
    }
}

关键修改说明:

  • 新增cornerRadius常量,可直接修改数值调整圆角弧度
  • 用bounds替代frame,避免视图布局时的坐标偏移问题
  • 对需要圆角的衔接点,使用addArc绘制圆弧过渡,替换原有的直线连接
  • 箭头尖端保留直线连接,维持尖锐形态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:10:22