Question

I'm working on an app where the main view fills up the whole screen. This main view contains subviews that you could think of as sprites. They wander around using their own code. The logic of how they wander around could have them wandering off screen. What I'd like to do is to resize the main view so that it encloses all the subviews. It's really not the view size that is changing, though. It is the scaling that is changing. Kind of like zooming out of a google maps view. How do I do that? It will be a gesture recognizer that triggers this.

Was it helpful?

Solution

You should do this using a three-level view hierarchy:

  • top-level view
    • scaled view
      • sprite view 0
      • sprite view 1
      • sprite view 2
      • etc.

Set the bounds of the scaled view to encompass the frames of all of the sprite views. Then set the transform of the scaled view so that it fits in the top-level view.

- (void)updateBoundsAndTransformOfView:(UIView *)scaledView {
    CGRect scaledBounds = CGRectNull;
    for (UIView *spriteView in scaledView.subviews) {
        scaledBounds = CGRectUnion(scaledBounds, spriteView.frame);
    }

    scaledView.bounds = scaledBounds;
    // Now scaledView's size is large enough to contain all of its subviews,
    // and scaledView's coordinate system origin is at the left edge of the
    // leftmost sprite and the top edge of the topmost sprite.

    UIView *topLevelView = scaledView.superview;
    CGRect topLevelBounds = topLevelView.bounds;
    CGFloat xScale =topLevelBounds.size.width / scaledBounds.size.width;
    CGFloat yScale = topLevelBounds.size.height / scaledBounds.size.height;
    CGFloat scale = MIN(xScale, yScale);
    scaledView.transform = CGAffineTransformMakeScale(scale, scale);
    scaledView.center = CGPointMake(CGRectGetMidX(topLevelBounds), CGRectGetMidY(topLevelBounds));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top