Search code examples
iosswiftuiviewuibezierpath

Border in circle UIView using Swift


I'm trying to make an UIView with border but I only make it appear in UIView not only on the circle.

sample

In the brown circle I want a black border, but it has to be in the circle not in the UIView.

I have a class called Ball where I draw the circle.

class Ball: UIView {

    var desiredColour = UIColor.blueColor()

    struct mine {
        static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,118,117))

    }

    override func drawRect(rect: CGRect) {
        // Drawing code


        desiredColour.setFill()
        mine.p.fill()

    }


    func colour() {

        var randColor: UIColor = Colors.randomColor()

        Colors.ballColor = randColor
        Colors.colorPosition = find(Colors.arrayColors, randColor)!

        desiredColour = randColor
        self.setNeedsDisplay()

    }
}

I used the code:

override func drawRect(rect: CGRect) {
    // Drawing code


    desiredColour.setFill()

    let desiredBorderColor = UIColor.blackColor()
    desiredBorderColor.setStroke()

    self.layer.borderWidth  = 3.0
    self.layer.cornerRadius = self.frame.size.width/2.0

    mine.p.fill()
    mine.p.stroke()

}

but i get a border with a little cuts:

enter image description here


Solution

  • override func drawRect(rect: CGRect) {
            // Drawing code
    
    
            desiredColour.setFill()
    
            let desiredBorderColor = UIColor.blackColor()
            desiredBorderColor.setStroke()
    
            mine.p.lineWidth = 2.0 //set to whatever you want
    
            mine.p.fill()
            mine.p.stroke()
    
        }
    

    But note that for border to work you need to have some space around you circle.

    Do the following. Declare myBorderWidth (of type CGFloat) property and then change

    static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,118,117))
    

    to

    static var p = UIBezierPath(ovalInRect: CGRectMake(myBorderWidth/2,myBorderWidth/2,118-myBorderWidth/2,117-myBorderWidth/2))
    

    You can also remove repetitions of myBorderWidth/2 by declaring it as a property.