带尖边的 UIView

UIView With Pointed Edges

我正在尝试制作一个像 this. Did some searching around and found some questions with slanting just one edge like 那样具有尖边的 UIView,但是找不到像图片中基于 UIView 高度动态调整大小的相交(点)边的答案。

我使用 Rob 的回答创建了这样的东西:

@IBDesignable
class PointedView: UIView
{
    @IBInspectable
    /// Percentage of the slant based on the width
    var slopeFactor: CGFloat = 15
    {
        didSet
        {
            updatePath()
        }
    }
    
    private let shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 0
        
        // with masks, the color of the shape layer doesn’t matter;
        // it only uses the alpha channel; the color of the view is
        // dictate by its background color
        shapeLayer.fillColor = UIColor.white.cgColor
        return shapeLayer
    }()
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        updatePath()
    }
    
    private func updatePath()
    {
        let path = UIBezierPath()
        
        // Start from x = 0 but the mid point of y of the view
        path.move(to: CGPoint(x: 0, y: bounds.midY))
        
        // Calculate the slant based on the slopeFactor
        let slantEndX = bounds.maxX * (slopeFactor / 100)
        
        // Create the top slanting line
        path.addLine(to: CGPoint(x: slantEndX, y: bounds.minY))
        
        // Straight line from end of slant to the end of the view
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        
        // Straight line to come down to the bottom, perpendicular to view
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        
        // Go back to the slant end position but from the bottom
        path.addLine(to: CGPoint(x: slantEndX, y: bounds.maxY))
        
        // Close path back to where you started
        path.close()
        
        shapeLayer.path = path.cgPath
        layer.mask = shapeLayer
    }
}

最终结果应该给你一个接近你可以在情节提要上修改的视图

也可以使用代码创建,这里是一个框架示例,因为故事板显示了它与自动布局的兼容性

private func createPointedView()
{
    let pointedView = PointedView(frame: CGRect(x: 0,
                                                y: 0,
                                                width: 200,
                                                height: 60))
    
    pointedView.backgroundColor = .red
    pointedView.slopeFactor = 50
    pointedView.center = view.center
    
    view.addSubview(pointedView)
}