jenny
jenny

Reputation: 191

How to fix uneven border width after view transformation?

Whenever I transform the box, the border widths become uneven.

enter image description here. enter image description here

I tried redrawing the frame after each transformation, but the issue still occurs. This is the relevant code:

@objc func pinchedView(_ sender:UIPinchGestureRecognizer){
    box.transform = box.transform.scaledBy(x: 1.0, y: sender.scale)
    box.frame = CGRect(x: box.frame.minX, y: box.frame.minY, width: box.frame.width, height: box.frame.height)
    box.layer.borderWidth = 1
    sender.scale = 1
}

So how do I maintain a constant border width after transformation?

Upvotes: 1

Views: 223

Answers (1)

Rob
Rob

Reputation: 437937

If you use transform to scale a view, that will scale everything, including the border. Instead, you’d just adjust the frame of the view.

E.g., if you defined your view’s frame directly (and you are not using constraints), then you would:

var oldHeight: CGFloat = 0

@objc func handlePinch(_ gesture: UIPinchGestureRecognizer) {
    switch gesture.state {
    case .began:
        oldHeight = subview.frame.height

    case .changed:
        subview.frame = CGRect(x: subview.frame.minX, y: subview.frame.minY, width: subview.frame.width, height: oldHeight * gesture.scale)

    default:
        break
    }
}

Or, if you were using constraints, you’d set up and @IBOutlet to the height constraint, for example, and then do something like:

@IBOutlet var heightConstraint: NSLayoutConstraint!

var oldHeight: CGFloat = 0

@objc func handlePinch(_ gesture: UIPinchGestureRecognizer) {
    switch gesture.state {
    case .began:
        oldHeight = heightConstraint.constant

    case .changed:
        heightConstraint.constant = oldHeight * gesture.scale

    default:
        break
    }
}

Upvotes: 3

Related Questions