Search code examples
iosswiftcgrect

How to change x and y of CGRect?


I draw a rectangle. When I touch screen, I can change width and height. By default I make x = 50, y = self.view.frame.height/2. I need to stretch rectangle relative to x and y. How can I change x and y?

var scanRectangleRect = CGRect.zero
var scanRectangle: UIView = UIView()


func drawLine() {
    self.view.addSubview(scanRectangle)
    scanRectangle.backgroundColor = UIColor.gray
    scanRectangleRect = CGRect(x: 50, y: self.view.frame.height/2, width: 400, height: 150)

    scanRectangle.frame  = scanRectangleRect
    scanRectangle.center = CGPoint(x: scanRectangle.center.x, y: self.view.frame.height/2)
    scanRectangle.isHidden = false
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    scanRectangle.frame.size.height += 10
    scanRectangle.frame.size.width += 10
}

Solution

  • let distance: CGFloat = 10
    scanRectangle.frame = CGRect(x: scanRectangle.frame.origin.x + distance, 
                                 y: scanRectangle.frame.origin.y + distance, 
                             width: scanRectangle.frame.size.width - distance, 
                            height: scanRectangle.frame.size.height - distance)
    

    I think what you mean is to scale the rectangle upon some base point.