Search code examples
swiftios8xcode6uibezierpath

Draw Ellipse in Swift using UIBezierPath


I have an UIViewController in which I want to draw a ellipse on the screen starting at CGPoint(x:160,y:160), width:240, height:320. How can I do that in swift? I would really much appreciate any help.


Solution

  • I believe this is what you are asking for:

    var ovalPath = UIBezierPath(ovalInRect: CGRectMake(160, 160, 240, 320))
    UIColor.grayColor().setFill()
    ovalPath.fill()
    

    For complex shapes I would suggest checking out PaintCode. It creates the swift code for you as you draw your shapes on screen (it has personally saved me a lot of time in the past).

    Edit:

    import Foundation
    import UIKit
    
    class CustomOval: UView {
    
        override func drawRect(rect: CGRect)
        {
                var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 240, 320))
                UIColor.grayColor().setFill()
                ovalPath.fill()
        }
    
    }
    

    Then :

    var exampleView = CustomOval()
    

    And then position it with constraints etc. afterwards.

    Swift 4

    var ovalPath = UIBezierPath(ovalIn: CGRect(x: 160, y: 160, width: 240, height: 320))
    UIColor.gray.setFill()
    ovalPath.fill()