Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent subviews from resizing when setting view's transform with CGAffineTransformScale()

Tags:

ios

If I do :

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

My view is scaled, but also its subviews... I don't want the subview to change size. Apparently autoresizesSubviews has no effect on this matter

like image 492
Thomas Joulin Avatar asked Nov 06 '22 02:11

Thomas Joulin


1 Answers

Suppose that your UIView's stack is arranged as follow:

@interface UIResizableView : UIView <UIGestureRecognizerDelegate> {
    UILabel *innerView;
    CGPoint startPoint;
}
@end

@implementation UIResizableView
- (id)initWithFrame:(CGRect)aFrame {
    self = [super initWithFrame:aFrame];
    if (self) {
    innerView = [[UILabel alloc] initWithFrame: CGRectMake(10, 10, 115, 50)];
    [innerView setFont:[UIFont systemFontWithSize:7]];
    [innerView setTextColor:[UIColor blackColor]];
    [innerView setBackgroundColor:[UIColor clearColor]];
    [innerView setTextAlignment:UITextAlignmentCenter];
    [innerView setText:@"hello world!"];
    [self innerView];
    [innerView release];

    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
    [pinchRecognizer setDelegate:self];
    [self addGestureRecognizer:pinchRecognizer];
    [pinchRecognizer release];
    }
    return self;
}
@end

Then your scale method would look like the following. Note that the "reframing" of innerView is required to center again the subview in the original position.

-(void)scale:(id)sender {
    static float lastScale = 0.0;
    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
        lastScale = 1.0;
        return;
    }
    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);

    CGAffineTransform currentTransform = self.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    [self setTransform:newTransform];

    CGAffineTransform originalSize = CGAffineTransformInvert(self.transform);
    CGAffineTransform originalPositionAndSize = CGAffineTransformTranslate(originalSize, self.frame.origin.x, self.frame.origin.y);
    [innerView setTransform:originalPositionAndSize];

    innerView = CGRectMake(10, 10, 115, 60);

    lastScale = [(UIPinchGestureRecognizer*)sender scale];
}
like image 176
valvoline Avatar answered Nov 09 '22 13:11

valvoline