swiftcgrectcgpoint

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

      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)