自动调整图像视图大小

时间:2014-05-10 16:58:04

标签: ios objective-c ipad uiscrollview uiimageview

我有一个scrollView和imageView。 该应用程序在横向和纵向模式下工作。 我使用自动布局。 如果我使用常量进行imageview。 我加载到imageviev中的图像会根据其大小自动扩展。

我现在拥有的:

风景模式: enter image description here

和肖像模式: enter image description here

我想在这些图片中制作

风景模式:

和肖像模式: enter image description here

如何修复imageview中的自动调整大小?

P.S。适用于iPad的应用程序

谢谢大家的答案!

1 个答案:

答案 0 :(得分:1)

以下是基于代码的Autolayout示例,可以帮助您

#import "UniversalViewController.h"

@interface UniversalViewController ()
@property (strong, nonatomic) UIImageView *myImageView;
@end

@implementation UniversalViewController
@synthesize myImageView;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];

    UIImage *myImage = [UIImage imageNamed:@"Velvet_Underground_and_Nico.jpg"];
    myImageView = [[UIImageView alloc] initWithImage:myImage];
    [myImageView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:myImageView];
    [self setWidth:300 andHeight:300 toView:myImageView];
    [self centerView1:myImageView toView2:self.view];
}

- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self.view removeConstraints:self.view.constraints];
    [self centerView1:myImageView toView2:self.view];
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [self setWidth:450 andHeight:250 toView:myImageView];
    } else {
        [self setWidth:300 andHeight:300 toView:myImageView];
    }
}

#pragma mark custom Autolayout methods
- (void) setWidth:(float)width andHeight:(float)height toView:(UIView *)view {

    NSLayoutConstraint *myConstraint;
    myConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:width];
    [self.view addConstraint:myConstraint];

    myConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:height];
    [self.view addConstraint:myConstraint];
}

- (void) centerView1:(UIView *)view1 toView2:(UIView *)view2 {
    NSLayoutConstraint *myConstraint;
    myConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0];
    [self.view addConstraint:myConstraint];

    myConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [self.view addConstraint:myConstraint];
}

您应该能够根据需要设置图像的大小...我希望它有所帮助...