KevinZ
KevinZ

Reputation: 766

How to center a UIBezierPath oval within a view of unknown width and height in Swift?

I am using the draw function in a custom UIView to create a custom texture. The issue is that the width and height are determined by a UIStackView. When I create the view I use CustomView(frame: CGRect(x: 0, y: 0, width: 50, height: 50, color: color) If the actual width and height are unknown at the time of the custom UIView uses the draw function. Is there a way to guarantee a UIBezierPath is centered within the bounds given by the UIStackView?

import Foundation 
import UIKit 
class CustomView: UIView {

        let color: UIColor

        required init(coder aDecoder: NSCoder) {
            color = UIColor()
            super.init(coder: aDecoder)!
        }
        init(frame: CGRect, color: UIColor) {
            self.color = color
            super.init(frame: frame)
            self.backgroundColor = UIColor.init(hexString: CustomColors.pale_blue)
        }

        override func draw(_ rect: CGRect) {

            color.setFill()
            color.setStroke()
            let width = Int(rect.size.width)
            let height = Int(rect.size.height)
            let yValue = Int(rect.origin.y)
            let xValue = Int(rect.origin.x)
            let rectBottom = UIBezierPath(rect: CGRect(x: xValue , y: yValue + height - (height/4), width: width, height: height/4))
            let ovalTop = UIBezierPath(ovalIn: CGRect(x: xValue + (width/4), y:yValue + (height/3), width: width/2, height: height/2))
            rectBottom.stroke()
            rectBottom.fill()
            ovalTop.fill()
            ovalTop.stroke()
        } 
}

Upvotes: 0

Views: 670

Answers (1)

Mustang
Mustang

Reputation: 417

At the time that your draw method is called, layout has already happened. Just look at self.bounds inside draw(). To be clear, don't look at the rect passed to draw to determine your geometry. You would only use that rect if you wanted to only redraw what bits needed updating.

Upvotes: 1

Related Questions