How to create a UIView oval?

advertisements

To make a circle view one must do

shapeView.layer.cornerRadius = CGFloat(width)/2.0

So I extended this logic to make an oval view

if width >= height {
    shapeView.layer.cornerRadius = CGFloat(width)/2.0
} else{
    shapeView.layer.cornerRadius = CGFloat(height)/2.0
}

Except my oval views have pointy ends as you can see here.

My question is: How do I get rid of the pointy ends and make them round?


If it's any concern I'm using:

  • Swift 2
  • IOS 9.2
  • Xcode 7.2

Use a CAShapeLayer as your layer mask:

class OvalView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        layoutOvalMask()
    }

    private func layoutOvalMask() {
        let mask = self.shapeMaskLayer()
        let bounds = self.bounds
        if mask.frame != bounds {
            mask.frame = bounds
            mask.path = CGPathCreateWithEllipseInRect(bounds, nil)
        }
    }

    private func shapeMaskLayer() -> CAShapeLayer {
        if let layer = self.layer.mask as? CAShapeLayer {
            return layer
        }
        let layer = CAShapeLayer()
        layer.fillColor = UIColor.blackColor().CGColor
        self.layer.mask = layer
        return layer
    }

}

Demo:

let backgroundView = UIView(frame: CGRectMake(0, 0, 450, 250))
backgroundView.backgroundColor = UIColor.redColor()
let ovalView = OvalView(frame: CGRectMake(25, 25, 400, 200))
backgroundView.addSubview(ovalView)
let imageView = UIImageView(image: UIImage(named: "image.jpg"))
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.frame = ovalView.bounds
ovalView.addSubview(imageView)

XCPlaygroundPage.currentPage.liveView = backgroundView

Result: