swift 如何使用AutoLayout制作四分之一圆[closed]

vdgimpew  于 2022-11-28  发布在  Swift
关注(0)|答案(2)|浏览(187)

已关闭。此问题需要更多focused。当前不接受答案。
**想要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。

2天前关闭。
Improve this question
如何使用Swift中的自动布局功能制作下图所示的象限(四分之一圆)?我知道需要使用UIBezierPath,但似乎无法使用。

tp5buhyn

tp5buhyn1#

快速、简单的示例:

class QuarterCircleView: UIView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // only add the shape layer once
        if layer.sublayers == nil {
            let lay = CAShapeLayer()
            lay.fillColor = UIColor.blue.cgColor
            layer.addSublayer(lay)
        }
        if let lay = layer.sublayers?.first as? CAShapeLayer {
            let center = CGPoint(x: bounds.midX, y: bounds.midY)
            let bez  = UIBezierPath()
            bez.move(to: center)
            bez.addArc(withCenter: center, radius: bounds.width * 0.5, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)
            bez.close()
            lay.path = bez.cgPath
        }
    }
    
}

注意:你真的应该在发布问题时展示你的尝试。搜索CAShapeLayer并阅读一些教程。

pxy2qtax

pxy2qtax2#

稍微修改一下DonMag的答案,使视图的图层成为CAShapeLayer,这样我们就不必担心添加子图层或检查现有的子图层:

class QuarterCircleView: UIView {

    // By adding this static var, we can change the type of our view's  layer (in this case, to a CAShapeLayer)
    static override var layerClass: AnyClass {
        return CAShapeLayer.self
    }

    // This lets us use the view's layer as a CAShapeLayer without type casting.
    var shapeLayer: CAShapeLayer {
        return self.layer as! CAShapeLayer
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        shapeLayer.fillColor = UIColor.blue.cgColor
    }

    // Every time we update our subviews, also regenerate our shape layer's path.
    override func layoutSubviews() {
        super.layoutSubviews()

        // We want a quarter-circle centered on the lower right of teh view.
        let center = CGPoint(x:bounds.maxX, y:bounds.maxY)
        let bez  = UIBezierPath()
        bez.move(to: center)

        // As long as our view is square, the below isn't needed, but let's be sure.
        let radius = min(bounds.width, bounds.height)
        bez.addArc(withCenter: center, radius: radius, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)
        bez.close()
        shapeLayer.path = bez.cgPath
    }

}

我的如下所示:(视图周围有一个1像素的边框,以便可以看到其边界:

相关问题