Search code examples
iosswiftdrawingcore-graphics

Why drawing straight lines using Core Graphics I get "dashed" lines?


I have tried to draw an icon with the following swift code but I got "dashed" lines. I have just used moveToPoint and addLineToPoint functions. I got the same graphic glitch with other drawing too as you can see in the under images. I use Xcode 7.2 and run code on iOS 9.2.1.

@IBDesignable class DeleteButton: UIButton {

    override func drawRect(rect: CGRect) {

        UIColor.blackColor().setStroke()
        let lineWidth = CGFloat(1)

        // Draw empty circle
        let frame = CGRect(x: rect.origin.x + lineWidth, y: rect.origin.y + lineWidth, width: rect.width - (lineWidth * 2), height: rect.height - (lineWidth * 2))
        let path = UIBezierPath(ovalInRect: frame)
        path.lineWidth = lineWidth

        path.stroke()

        // Draw X
        let radius = (rect.width / 2) * 0.5
        let center = CGPoint(x: rect.width / 2, y: rect.height / 2)

        let π = CGFloat(M_PI)
        let centerWidth = radius * cos(π/4)
        let centerHeight = radius * sin(π/4)

        path.lineWidth = lineWidth

        path.moveToPoint(CGPoint(x: CGFloat(center.x + centerWidth), y: CGFloat(center.y + centerHeight)))
        path.addLineToPoint(CGPoint(x: CGFloat(center.x - centerWidth), y: CGFloat(center.y - centerHeight)))
        path.stroke()

        path.lineWidth = lineWidth

        path.moveToPoint(CGPoint(x: center.x - centerWidth, y: center.y + centerHeight))
        path.addLineToPoint(CGPoint(x: center.x + centerWidth, y: center.y - centerHeight))
        path.stroke()
    }
}

This is the result:

I apologize for my bad english.


Solution

  • I believe you are seeing the result of the button's title text drawing over the image. Check out the following demo using your code in a Playground:

    enter image description here