【问题标题】:Dashed horizontal line using IBDesignable使用 IBDesignable 的水平虚线
【发布时间】:2019-01-14 09:06:02
【问题描述】:

所以我遇到了this 问题,我想用@IBDesignable 以相同的方法绘制一条水平线。

我曾尝试在课堂上玩耍,但没有结果。

@IBDesignable class DottedVertical: UIView {

    @IBInspectable var dotColor: UIColor = UIColor.etc
    @IBInspectable var lowerHalfOnly: Bool = false

    override func draw(_ rect: CGRect) {

        // say you want 8 dots, with perfect fenceposting:
        let totalCount = 8 + 8 - 1
        let fullHeight = bounds.size.height
        let width = bounds.size.width
        let itemLength = fullHeight / CGFloat(totalCount)

        let path = UIBezierPath()

        let beginFromTop = CGFloat(0.0)
        let top = CGPoint(x: width/2, y: beginFromTop)
        let bottom = CGPoint(x: width/2, y: fullHeight)

        path.move(to: top)
        path.addLine(to: bottom)

        path.lineWidth = width

        let dashes: [CGFloat] = [itemLength, itemLength]
        path.setLineDash(dashes, count: dashes.count, phase: 0)

        // for ROUNDED dots, simply change to....
        //let dashes: [CGFloat] = [0.0, itemLength * 2.0]
        //path.lineCapStyle = CGLineCap.round

        dotColor.setStroke()
        path.stroke()
    }
}

【问题讨论】:

    标签: ios swift uikit core-animation


    【解决方案1】:

    你可以实现如下,

    @IBDesignable class DottedHorizontal: UIView {
    
        @IBInspectable var dotColor: UIColor = UIColor.red
        @IBInspectable var lowerHalfOnly: Bool = false
    
        override func draw(_ rect: CGRect) {
    
            let fullHeight = bounds.size.height
            let width = bounds.size.width
    
            let path = UIBezierPath()
    
            path.move(to: CGPoint(x: 0, y: fullHeight/2))
            path.addLine(to: CGPoint(x: width, y: fullHeight/2))
    
            path.lineWidth = 5
    
            let dashes: [CGFloat] = [4, 2]
            path.setLineDash(dashes, count: dashes.count, phase: 0)
    
            dotColor.setStroke()
            path.stroke()
        }
    }
    

    【讨论】:

    • 但高度不是视图的全高
    • lineWidth = 5 更改为lineWidth = fullHeight
    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多