aac
aac

Reputation: 31

Keep zoom centered on UIView center (as opposed to scaling from top left corner)

I am implementing a pinch-based zoom and the scaling occurs from the top left corner of the view as opposed to scaling from the center. After a few attempts (this seems like a cs origin problem or the like), not finding a good solution for this but there must be some (perhaps obvious) way to scale from the view's center. If this has been answered before, would appreciate a pointer to the answer (not found after extensive search). If not, will appreciate inputs on correct approach.

Edit following answers (thanks): Here is the code I was initially using:

func pinchDetected(pinchGestureRecognizer: UIPinchGestureRecognizer) {

    let scale = pinchGestureRecognizer.scale
    view.transform = CGAffineTransformScale(view.transform, scale, scale)
    pinchGestureRecognizer.scale = 1.0

}

Upon pinch, the content inside the view would be expanding rightward and downward as opposed to same + leftward and upward (hence the assumption it is not scaling "from the center"). Hope this makes it clearer.

Upvotes: 0

Views: 1842

Answers (3)

DavidEC
DavidEC

Reputation: 136

It's hard to know whats going on without seeing your code. By default transforms do act on a views centre, which seems to be what you want. You can make the transforms act on some other point by changing the anchorPoint property on the views layer.

Or you can create a transform about an arbitrary point by translating the origin to that point, doing your transform, and translating back again. e.g:

func *(left: CGAffineTransform, right: CGAffineTransform) -> CGAffineTransform {
    return left.concatenating(right)
}


public extension CGAffineTransform {
    static func scale(_ scale:CGFloat, aboutPoint point:CGPoint) -> CGAffineTransform {
        let Tminus = CGAffineTransform(translationX: -point.x, y: -point.y)
        let S = CGAffineTransform(scaleX: scale, y: scale)
        let Tplus = CGAffineTransform(translationX: point.x, y: point.y)
    
        return Tminus * S * Tplus
    }
}

view.transform = CGAffineTransform.scale(2.0, aboutPoint:point)

where the point is relative to the origin, which by default is the center.

Upvotes: 1

Daniel Legler
Daniel Legler

Reputation: 527

You should be able to just use the code in this question to get it to zoom from the center. If you want it to zoom from the fingers, see the answer to that question.

Upvotes: 0

Naresh
Naresh

Reputation: 344

This is the code you are looking for

view.transform = CGAffineTransformScale(view.transform, 1.1, 1.1);

or in Swift

view.transform = view.transform.scaledBy(x: 1.1, y: 1.1)

This will increase views height and width by the provided scale. Now you can control the amount by using a gesture recognizer.

Upvotes: 0

Related Questions