UIImageView无法正确旋转?

时间:2012-05-08 18:27:41

标签: iphone objective-c ios uiimageview

我在UIViewController中有一个UIScrollView。它启用了滚动和缩放功能。它包含一个UIImageView,当用户旋转设备时,想法是图像保持居中。问题是,当设备旋转时,它实际上显示在左侧而不是中心,它应该停留在那里。这是我正在使用的代码。当UIScrollView旋转时调用设置框架:

-(void)setFrame:(CGRect)frame {

    float previousWidth = self.frame.size.width;
    float newWidth = frame.size.width;

    [super setFrame:frame];
    self.imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

    [self setupScales];

    self.zoomScale = self.zoomScale * (newWidth / previousWidth);
}

3 个答案:

答案 0 :(得分:1)

我在uiscrollview的子类中使用以下layoutsubviews方法:

- (void)layoutSubviews {
    [super layoutSubviews];

    if ([[self subviews] count] == 0) {
        return;
    }

    // center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = self.bounds.size;
    CGRect frameToCenter = ((UIView*)[[self subviews] objectAtIndex:0]).frame;

    // center horizontally
    if (frameToCenter.size.width < boundsSize.width)
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
        frameToCenter.origin.x = 0;

    // center vertically
    if (frameToCenter.size.height < boundsSize.height)
        frameToCenter.origin.y = ((boundsSize.height - frameToCenter.size.height) / 2);
    else
        frameToCenter.origin.y = 0;

    ((UIView*)[[self subviews] objectAtIndex:0]).frame = frameToCenter;
}

答案 1 :(得分:0)

您可能还需要设置滚动视图的contentOffset属性

答案 2 :(得分:0)

如果scrollview通过方向更改调整大小,请尝试使用

self.imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;