画个括弧

2017-04-06  本文已影响6人  轻云绿原

画了个括弧,分享一下。

import UIKit

class IndicatrixCollectionReusableView: UICollectionReusableView {
    
    var insets:UIEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    /// 线宽
    var lineWidth:CGFloat = 1
    /// 线颜色
    var strokeColor = UIColor.black
    /// 转角半径
    var radius:CGFloat = 7
    var isLine:Bool = false
    
    override func draw(_ rect: CGRect) {
        guard rect.height >= insets.top + insets.bottom + radius * 2 else{
            fatalError("IndicatrixCollectionReusableView 高度不够。")
        }
        
        let centerX = rect.midX
        let centerY = rect.midY
        let top = insets.top
        let bottom = insets.bottom
        
        
        if insets.left + 2 * radius > centerX || rect.width - (insets.right + 2 * radius) < centerX{
            if !isLine{
                isLine = true
            }
        }

        let linePath = UIBezierPath()
        var point:CGPoint
        
        if isLine{
            point = CGPoint(x: centerX, y: top)
            linePath.move(to: point)
            
            point.y = rect.height - bottom
            linePath.addLine(to: point)
        }else{
            
            point = CGPoint(x: insets.left, y: rect.height - bottom)
            linePath.move(to: point)
            
            
            point.y = rect.height / 2 + radius
            linePath.addLine(to: point)
            
            point.x += radius
            linePath.addArc(withCenter: point, radius: radius, startAngle: CGFloat(M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
            
            point.x = centerX - radius
            point.y = centerY
            linePath.addLine(to: point)
            
            point.y -= radius
            linePath.addArc(withCenter: point, radius: radius, startAngle: CGFloat(M_PI_2), endAngle: 0, clockwise: false)
            
            point.x += radius
            point.y = top
            linePath.addLine(to: point)
            
            point.y = centerY - radius
            linePath.addLine(to: point)
            
            point.x += radius
            linePath.addArc(withCenter: point, radius: radius, startAngle: CGFloat(M_PI), endAngle: CGFloat(M_PI_2), clockwise: false)
            
            point.y = centerY
            point.x = rect.width - insets.right - radius
            linePath.addLine(to: point)
            
            point.y += radius
            linePath.addArc(withCenter: point, radius: radius, startAngle: CGFloat(-M_PI_2), endAngle: 0, clockwise: true)
            
            point.x += radius
            point.y = rect.height - insets.bottom
            linePath.addLine(to: point)
        }
        linePath.lineJoinStyle = .round
        linePath.lineCapStyle = .round
        linePath.lineWidth = lineWidth
        
        // stroke应该放最后,不然上面的属性设置不起作用
        strokeColor.setStroke()
        linePath.stroke()
    }
}

效果如下:

括弧效果
上一篇 下一篇

猜你喜欢

热点阅读