Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to centre rectangle in view

I want to centre a rectangle in a view, i try using midX or midY but the view still not centre

overlay rect

this is how i setup the rectangle
the overlayView have width = 414 and height = 688

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let midX = overlayView.bounds.midX
        let midY = overlayView.bounds.midY
        let center = CGPoint(x: midX, y: midY)
        let size: CGFloat = 312
        
        // Create the initial layer from the view bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = overlayView.bounds

        // Create the path.
        let rect = CGRect(x: center.x, y: center.y, width: size, height: size)
        let path = UIBezierPath(rect: overlayView.bounds)
        
        maskLayer.fillRule = .evenOdd

        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(roundedRect: rect, cornerRadius: 20))
        maskLayer.path = path.cgPath

        // Set the mask of the view.
        overlayView.layer.mask = maskLayer
    }

I already try to calculate the center but still can’t get the rect in the centre.

>Solution :

You have to subtract half-height and width from the center, as you have set start x and y position from the center point

so change your rect code.

let rect = CGRect(x: center.x - size/2, y: center.y - size/2, width: size, height: size)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading