점선

2017-05-08 4 views
2
이 같은 전망의 주위에 모서리가 둥근 점선을 그릴 노력하고

:점선

class DashedLineView: UIView { 

    override func draw(_ rect: CGRect) { 

     let path = UIBezierPath(roundedRect: rect, cornerRadius: 8) 

     UIColor.clear.setFill() 
     path.fill() 

     UIColor.red.setStroke() 
     path.lineWidth = 3 

     let dashPattern : [CGFloat] = [3, 3] 
     path.setLineDash(dashPattern, count: 2, phase: 0) 
     path.stroke() 
    } 
} 

결과는 다음과 같습니다

enter image description here

가 당신이 볼 수 있듯이 모서리에 문제가 있습니다. 어떤 문제를 해결할 수 있을까요?

업데이트 : @ 존 로즈 answer를 사용 DashedLineView 이제 다음과 같습니다

class DashedLineView: UIView { 

    private let borderLayer = CAShapeLayer() 

    override func awakeFromNib() { 

     super.awakeFromNib() 

     borderLayer.strokeColor = UIColor.red.cgColor 
     borderLayer.lineDashPattern = [3,3] 
     borderLayer.backgroundColor = UIColor.clear.cgColor 
     borderLayer.fillColor = UIColor.clear.cgColor 

     layer.addSublayer(borderLayer) 
    } 

    override func draw(_ rect: CGRect) { 

     borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: 8).cgPath 
    } 
} 
+0

drawRect 대신 CAShaperLayer를 사용하는 것이 좋습니다. 나는 이것을 CAShaperLayer와 경로를 사용하여 구현했으며 잘 보입니다. –

+0

예제를 게시 할 수 있습니까? – sash

답변

3

나는 CAShapeLayer를 사용하여 좋은 경험이 있었다. 예를 들어 :

let rect = CGRect.init(origin: CGPoint.init(x: 20, y: 100), size: CGSize.init(width: 200, height: 100)) 
let layer = CAShapeLayer.init() 
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8) 
layer.path = path.cgPath; 
layer.strokeColor = UIColor.red.cgColor; 
layer.lineDashPattern = [3,3]; 
layer.backgroundColor = UIColor.clear.cgColor; 
layer.fillColor = UIColor.clear.cgColor; 
self.view.layer.addSublayer(layer); 

보너스로 거의 모든 CAShapeLayer의 속성이 대시 박스 주위에 이동하는 것처럼 보이게 만들 수 있다는 뜻 lineDashPhase 등 애니메이션이다.