簡體   English   中英

用貝塞爾曲線繪制UIView

[英]Draw UIView with bezier path

如何繪制如下圖所示的視圖

設計

我想要UIView像圖片中的注解視圖,
我知道從設計器中獲取圖像並將其分配到UIImageView中 ,但我不想這樣做,也不需要彈出顯示。

我想通過UIBezierPath或其他方法通過UIView進行此操作。

幫助將不勝感激,並預先感謝!

您可以嘗試以下方法:

class PopUpView: UIView {

    override func draw(_ rect: CGRect) {

        let width: CGFloat = rect.width
        let height: CGFloat = rect.height

        let radius: CGFloat = 8
        let arrowRadius: CGFloat = 4

        let arrowWidth: CGFloat = 24
        let arrowHeight: CGFloat = 18

        let startingPoint = CGPoint(x: radius, y: 0)
        let upperRightCenter = CGPoint(x: width - radius, y: radius)
        let bottomRightCenter = CGPoint(x: width - radius, y: height - radius - arrowHeight)
        let bottomLeftCenter = CGPoint(x: radius, y: height - radius - arrowHeight)
        let upperLeftCenter = CGPoint(x: radius, y: radius)

        let path: UIBezierPath = UIBezierPath()

        path.move(to: startingPoint)

        path.addArc(withCenter: upperRightCenter, radius: radius, startAngle: 270.degreesToRadians, endAngle: 0, clockwise: true)

        path.addArc(withCenter: bottomRightCenter, radius: radius, startAngle: 0, endAngle: 90.degreesToRadians, clockwise: true)

        path.addArc(withCenter: CGPoint(x: (width + arrowWidth)/2 + arrowRadius, y: height + arrowRadius - arrowHeight), radius: arrowRadius, startAngle: 270.degreesToRadians, endAngle: 225.degreesToRadians, clockwise: false)

        path.addArc(withCenter: CGPoint(x: width/2, y: height - arrowRadius), radius: arrowRadius, startAngle: 45.degreesToRadians, endAngle: 135.degreesToRadians, clockwise: true)

        path.addArc(withCenter: CGPoint(x: (width - arrowWidth)/2 - arrowRadius, y: height + arrowRadius - arrowHeight), radius: arrowRadius, startAngle: 315.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: false)

        path.addArc(withCenter: bottomLeftCenter, radius: radius, startAngle: 90.degreesToRadians, endAngle: 180.degreesToRadians, clockwise: true)

        path.addArc(withCenter: upperLeftCenter, radius: radius, startAngle: 180.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true)

        path.close()

        UIColor.gray.setFill()
        UIColor.clear.setStroke()

        path.fill()
        path.stroke()
    }

}

extension Int {
    var degreesToRadians: CGFloat {
        return CGFloat(M_PI) * CGFloat(self) / 180.0
    }
}

基本上,我繼承了UIView的子類,覆蓋了drawRect方法,並使用UIBezierPath創建了相似的形狀。 您可能需要更改我用來滿足您的要求的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM