使用CGAffineTransformScale()设置视图变换时防止子视图调整大小

时间:2011-02-15 13:17:20

标签: ios

如果我这样做:

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

我的视图已缩放,但也是其子视图...我不希望子视图更改大小。显然autoresizesSubviews对此事没有影响

2 个答案:

答案 0 :(得分:2)

假设你的UIView的堆栈安排如下:

@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

然后您的缩放方法如下所示。请注意,innerView的“重构”需要将子视图再次置于原始位置。

-(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];
}

答案 1 :(得分:0)

在父视图上应用转换后,可能正在添加子视图(并使用父视图的帧值来设置大小)。至少这就是我在做的事情。

我必须通过应用反演来弥补这一点

CGRect parentOriginalFrame = CGRectApplyAffineTransform(parentView.frame, CGAffineTransformInvert(parentView.transform));

现在使用父级的原始帧,您可以为子级设置正确的帧值。