简体   繁体   English

UIImageView无法正确旋转?

[英]UIImageView not rotating correctly?

I have a UIScrollView inside a UIViewController. 我在UIViewController中有一个UIScrollView。 It has scrolling and zooming enabled. 它启用了滚动和缩放。 It contains a UIImageView and when the user rotates the device, the idea is that the image stays centered. 它包含一个UIImageView,并且当用户旋转设备时,其想法是图像保持居中。 The problem is, when the device is rotated, it actually appears off to the left instead of center, where it should be staying. 问题是,旋转设备时,它实际上显示在左侧而不是应该停留的中心位置。 Here is the code I'm using. 这是我正在使用的代码。 Set frame is called when the UIScrollView rotates: 当UIScrollView旋转时,将调用Set框架:

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

I use the following layoutsubviews method in my subclass of uiscrollview: 我在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;
}

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

如果滚动视图的大小随着方向的改变而改变,请尝试以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM