【问题标题】:Shape a triangle with UIView backed by CAShapeLayer用 CAShapeLayer 支持的 UIView 塑造一个三角形
【发布时间】:2025-12-25 07:40:16
【问题描述】:

从教程:http://swiftiostutorials.com/tutorial-draw-nice-triangle-view-border-cashapelayer/,我设法创建了一个三角形:

class Triangle: UIView {
    override func drawRect(rect: CGRect) {
        let mask = CAShapeLayer()
        mask.frame = self.layer.bounds

        let width = self.layer.frame.size.width
        let height = self.layer.frame.size.height

        let path = CGPathCreateMutable()

        CGPathMoveToPoint(path, nil, 0, 0)
        CGPathAddLineToPoint(path, nil, width, 0)
        CGPathAddLineToPoint(path, nil, width, height)
        CGPathAddLineToPoint(path, nil, width/2, height)
        CGPathAddLineToPoint(path, nil, width, height)


        mask.path = path
        self.layer.mask = mask
    }
}

但我想要实现的是像这样的三角形:

如何做到这一点?

【问题讨论】:

    标签: ios swift xcode cashapelayer


    【解决方案1】:

    改用此路径:

    CGPathMoveToPoint(path, nil, 0, 0)
    CGPathAddLineToPoint(path, nil, width, 0)
    CGPathAddLineToPoint(path, nil, width/2, height)
    CGPathAddLineToPoint(path, nil, 0, 0)
    

    全班:

    class Triangle: UIView {
        override func drawRect(rect: CGRect) {
            let mask = CAShapeLayer()
            mask.frame = self.layer.bounds
    
            let width = self.layer.frame.size.width
            let height = self.layer.frame.size.height
    
            let path = CGPathCreateMutable()
    
            CGPathMoveToPoint(path, nil, 0, 0)
            CGPathAddLineToPoint(path, nil, width, 0)
            CGPathAddLineToPoint(path, nil, width/2, height)
            CGPathAddLineToPoint(path, nil, 0, 0)
    
            mask.path = path
            self.layer.mask = mask
        }
    }
    

    【讨论】:

    • 啊,没注意到多余的CGPathAddLineToPoint。谢谢,伙计!
    最近更新 更多