如何将imageView框架的矩形作为目标c中的子视图

时间:2017-02-05 07:11:48

标签: ios

如何将imageView框架的矩形作为目标c中的子视图? 内部视图控制器我有一个视图,在该视图中我想放置一个imageView,而imageView框架应该小于视图框架的框架,而imageView应该位于视图框架的中心。

1 个答案:

答案 0 :(得分:0)

首先,设置imageView的大小,辅助,设置imageView的坐标,这里是代码:

    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    container.backgroundColor = [UIColor blueColor];
    [self.view addSubview:container];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.backgroundColor = [UIColor redColor];
    [container addSubview:imageView];

    CGRect f = imageView.frame;
    f.origin.x = CGRectGetWidth(container.bounds) / 2.0f - CGRectGetWidth(f) / 2.0;
    f.origin.y = CGRectGetHeight(container.bounds) / 2.0f - CGRectGetHeight(f) / 2.0f;
    imageView.frame = f;

或设置imageView的中心(提醒!imageView添加到self.view!)

    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    container.backgroundColor = [UIColor blueColor];
    [self.view addSubview:container];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:imageView];

    imageView.center = container.center;

此外,您可以使用autolayout,如下所示:

    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    container.backgroundColor = [UIColor blueColor];
    [self.view addSubview:container];

    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.backgroundColor = [UIColor redColor];
    [container addSubview:imageView];
    imageView.translatesAutoresizingMaskIntoConstraints = NO;

    NSLayoutConstraint *c1 = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:100];
    NSLayoutConstraint *c2 = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:100];
    NSLayoutConstraint *c3 = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:container attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *c4 = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:container attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    c1.active = YES;
    c2.active = YES;
    c3.active = YES;
    c4.active = YES;

上述所有解决方案都会将imageView置于container

的中心

result1