Drawing an ellipse in Swift using UIBezierPath

I have UIViewController

, which I want to draw an ellipse on the screen, since CGPoint(x:160,y:160)

, width: 240

, height: 320

. How can I do this quickly? I would really appreciate any help.

+6


source to share


3 answers


I believe this is what you are asking:

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

      

For complex shapes, I would suggest checking PaintCode . It generates quick code for you when you draw your shapes to the screen (this 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 put that with constraints, etc. Subsequently.

Swift 4

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

      

+14


source


Write this code to override func drawRect (rect: CGRect) in your custom UIView and then edit as you like.



override func drawRect(rect: CGRect) {
    let ellipsePath = UIBezierPath(ovalInRect: CGRectMake(100, 100, 100, 200))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = ellipsePath.CGPath
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.blueColor().CGColor
    shapeLayer.lineWidth = 5.0

    self.layer.addSublayer(shapeLayer)
}

      

+3


source


let shapeLayer = CAShapeLayer()
shapeLayer.path = ovalPath.cgPath 
shapeLayer.fillColor = UIColor.clear.cgColor 
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 5.0 self.layer.addSublayer(shapeLayer)

      

0


source







All Articles