使用Aspect Fit对齐UIImageView

时间:2010-07-17 16:35:42

标签: iphone cocoa-touch interface-builder

对于我的UIImageView我选择Aspect Fit(InterfaceBuilder)但是如何更改垂直对齐?

11 个答案:

答案 0 :(得分:40)

[编辑 - 此代码从2011年开始有点发霉,除了我合并@ ArtOfWarefare的mods之外]

你不能用UIImageView这样做。我创建了一个包含UIImageView的简单UIView子类MyImageView。代码如下。

// MyImageView.h
#import <UIKit/UIKit.h>

@interface MyImageView : UIView {
    UIImageView *_imageView;
}

@property (nonatomic, assign) UIImage *image;

@end

// MyImageView.m

#import "MyImageView.h"

@implementation MyImageView

@dynamic image;

- (id)initWithCoder:(NSCoder*)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.clipsToBounds = YES;
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:_imageView];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:_imageView];
    }
    return self;
}

- (id)initWithImage:(UIImage *)anImage
{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        _imageView.image = anImage;
        [_imageView sizeToFit];

        // initialize frame to be same size as imageView
        self.frame = _imageView.bounds;        
    }
    return self;
}

// Delete this function if you're using ARC
- (void)dealloc
{
    [_imageView release];
    [super dealloc];
}

- (UIImage *)image
{
    return _imageView.image;
}

- (void)setImage:(UIImage *)anImage
{
    _imageView.image = anImage;
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
    if (!self.image) return;

    // compute scale factor for imageView
    CGFloat widthScaleFactor = CGRectGetWidth(self.bounds) / self.image.size.width;
    CGFloat heightScaleFactor = CGRectGetHeight(self.bounds) / self.image.size.height;

    CGFloat imageViewXOrigin = 0;
    CGFloat imageViewYOrigin = 0;
    CGFloat imageViewWidth;
    CGFloat imageViewHeight;


    // if image is narrow and tall, scale to width and align vertically to the top
    if (widthScaleFactor > heightScaleFactor) {
        imageViewWidth = self.image.size.width * widthScaleFactor;
        imageViewHeight = self.image.size.height * widthScaleFactor;
    }

    // else if image is wide and short, scale to height and align horizontally centered
    else {
        imageViewWidth = self.image.size.width * heightScaleFactor;
        imageViewHeight = self.image.size.height * heightScaleFactor;
        imageViewXOrigin = - (imageViewWidth - CGRectGetWidth(self.bounds))/2;
    }

    _imageView.frame = CGRectMake(imageViewXOrigin,
                                  imageViewYOrigin,
                                  imageViewWidth,
                                  imageViewHeight);
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self setNeedsLayout];
}

@end

答案 1 :(得分:30)

如果使用Storyboard,可以通过限制来实现......

首先是具有所需最终帧/约束的UIView。将UIImageView添加到UIView。将contentMode设置为Aspect Fill。使UIImageView框架与图像的比例相同(这可以避免以后的任何Storyboard警告)。使用标准约束将边固定到UIView。使用标准约束将顶部或底部(取决于您想要对齐的位置)固定到UIView。最后将一个宽高比约束添加到UIImageView(确保比率为图像)。

答案 2 :(得分:9)

这有点棘手,因为如果您已选择内容模式(.scaleAspectFit),则无法设置更多对齐规则。

但是这是一个解决方法:

首先需要通过计算维度来明确调整源图像的大小(如果它位于带UIImageView的{​​{1}}中。

contentMode = .scaleAspectFit

然后,只需通过传递imageView的框架并将结果分配给extension UIImage { func aspectFitImage(inRect rect: CGRect) -> UIImage? { let width = self.size.width let height = self.size.height let aspectWidth = rect.width / width let aspectHeight = rect.height / height let scaleFactor = aspectWidth > aspectHeight ? rect.size.height / height : rect.size.width / width UIGraphicsBeginImageContextWithOptions(CGSize(width: width * scaleFactor, height: height * scaleFactor), false, 0.0) self.draw(in: CGRect(x: 0.0, y: 0.0, width: width * scaleFactor, height: height * scaleFactor)) defer { UIGraphicsEndImageContext() } return UIGraphicsGetImageFromCurrentImageContext() } } 属性,即可在原始图像上调用此函数。另外,请确保在此处设置imageView所需的UIImageView.image,甚至在Interface Builder 中)!

contentMode

答案 3 :(得分:8)

尝试设置:

imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.clipsToBounds = YES;

这对我有用。

答案 4 :(得分:3)

由于开发人员

,我使用UIImageViewAligned来改变图像的对齐方式

UIImageViewAligned

答案 5 :(得分:2)

我知道这是一个老线程,但我想我会分享我在Interface Builder中从图像视图的顶部到底部轻松更改剪切区域,以防万一我遇到同样的问题。我有一个UIImageView填充了我的ViewController视图,并试图使顶部保持不变,与设备屏幕的大小无关。

  1. 我应用了视网膜4形状因子(Editor-&gt; Apply Retina 4 Form Factor)。

  2. 我固定了高度和宽度。

  3. 现在,当屏幕改变大小时,UIImageView实际上是相同的大小,视图控制器只是剪辑屏幕外的内容。帧原点保持为0,0,因此图像的底部和右侧被剪裁,而不是顶部。

    希望这有帮助。

答案 6 :(得分:1)

您可以先缩放然后调整大小。 这里要提到的是我受到身高的限制。我的意思是,我必须有34px高的图像,无论宽度如何。

因此,获取实际内容高度与视图高度之间的比率(34像素),然后也缩放宽度。

我是这样做的:

CGSize size = [imageView sizeThatFits:imageView.frame.size];

CGSize actualSize;
actualSize.height = imageView.frame.size.height;
actualSize.width = size.width / (1.0 * (size.height / imageView.frame.size.height));

CGRect frame = imageView.frame;
frame.size = actualSize;
[imageView setFrame:frame];

希望这有帮助。

答案 7 :(得分:1)

我想到了以下解决方案:

  1. UIImageView内容模式设置为topimageView.contentMode = .top
  2. 调整图像大小以适合UIImageView边界

要加载和调整图像大小,请使用Kingfisher

let size = imageView.bounds.size
let processor = ResizingImageProcessor(referenceSize: size, mode: .aspectFit)
imageView.kf.setImage(with: URL(string: imageUrl), options: [.processor(processor)])

答案 8 :(得分:0)

我通过继承UIImageView并重写setImage:方法解决了这个问题。子类首先存储原始值和大小的原始值,以便它可以使用原始集大小作为边界框。

我将内容模式设置为UIViewContentModeAspectFit。在setImage里面:我抓住图像的宽高比,然后调整图像视图的大小以适应与图像相同的比例。调整大小后,我调整了我的帧属性,将图像视图设置在之前的相同位置,然后我调用了超级setImage:。

这会导致图像视图的框架被调整为精确匹配图像,因此纵横比适合工作,图像视图框架属性在将图像视图放在应该达到相同效果的位置时进行了繁重的工作。 / p>

以下是我使用的一些代码:

首先,我发现它非常有用,是UIView上的一个类别,它可以通过左,右,顶部,底部,宽度,高度等属性轻松设置视图的框架属性。

的UIImageView + FrameAdditions

@interface UIView (FrameAdditions)

@property CGFloat left, right, top, bottom, width, height;
@property CGPoint origin;

@end

@implementation UIView (FrameAdditions)

- (CGFloat)left {
    return self.frame.origin.x;
}

- (void)setLeft:(CGFloat)left {
    self.frame = CGRectMake(left, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}

- (CGFloat)right {
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setRight:(CGFloat)right {
    self.frame = CGRectMake(right - self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
}

- (CGFloat)top {
    return self.frame.origin.y;
}

- (void)setTop:(CGFloat)top {
    self.frame = CGRectMake(self.frame.origin.x, top, self.frame.size.width, self.frame.size.height);
}

- (CGFloat)bottom {
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setBottom:(CGFloat)bottom {
    self.frame = CGRectMake(self.frame.origin.x, bottom - self.frame.size.height, self.frame.size.width, self.frame.size.height);
}

- (CGFloat)width {
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width, self.frame.size.height);
}

- (CGFloat)height {
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height {
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, height);
}

- (CGPoint)origin {
    return self.frame.origin;
}

- (void)setOrigin:(CGPoint)origin {
    self.frame = CGRectMake(origin.x, origin.y, self.frame.size.width, self.frame.size.height);
}

@end

这是UIImageView的子类。它没有经过全面测试,但应该了解这个想法。这可以扩展为设置自己的新对齐模式。

BottomCenteredImageView

@interface BottomCenteredImageView : UIImageView

@end


@interface BottomCenteredImageView() {
    CGFloat originalLeft;
    CGFloat originalBottom;
    CGFloat originalHeight;
    CGFloat originalWidth;
}

@end

@implementation BottomCenteredImageView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

- (void)awakeFromNib {
    [self initialize];
}

- (void)initialize {
    originalLeft = self.frame.origin.x;
    originalHeight = CGRectGetHeight(self.frame);
    originalWidth = CGRectGetWidth(self.frame);
    originalBottom = self.frame.origin.y + originalHeight;
}

- (void)setImage:(UIImage *)image {
    if(image) {
        self.width = originalWidth;
        self.height = originalHeight;
        self.left = originalLeft;
        self.bottom = originalBottom;

        float myWidthToHeightRatio = originalWidth/originalHeight;
        float imageWidthToHeightRatio = image.size.width/image.size.height;
        if(myWidthToHeightRatio >= imageWidthToHeightRatio) {
            // Calculate my new width
            CGFloat newWidth = self.height * imageWidthToHeightRatio;
            self.width = newWidth;
            self.left = originalLeft + (originalWidth - self.width)/2;
            self.bottom = originalBottom;
        } else {
            // Calculate my new height
            CGFloat newHeight = self.width / imageWidthToHeightRatio;
            self.height = newHeight;
            self.bottom = originalBottom;
        }
        self.contentMode = UIViewContentModeScaleAspectFit;
        [super setImage:image];
    } else {
        [super setImage:image];
    }
}

@end

答案 9 :(得分:0)

如果您需要实现AspectFit并消除空白空间

别忘了从情节提要中删除图像视图的宽度约束并享受

SelfSizedImageView类:UIImageView {

override func layoutSubviews() {
    super.layoutSubviews()

    guard let imageSize = image?.size else {
        return
    }

    let viewBounds = bounds
    let imageFactor = imageSize.width / imageSize.height
    let newWidth = viewBounds.height * imageFactor

    let myWidthConstraint = self.constraints.first(where: { $0.firstAttribute == .width })
    myWidthConstraint?.constant = min(newWidth, UIScreen.main.bounds.width / 3)

    layoutIfNeeded()
}}

答案 10 :(得分:-4)

要对齐缩放比例图像,请使用自动布局。在UIImageView中按比例缩放后右对齐图像的示例:

  1. 创建保存图像的UIImageView
  2. 为右,上,下,宽
  3. 添加自动约束
  4. 设置图片:
  5. myUIImageView.contentMode = .ScaleAspectFit
    myUIImageView.translatesAutoresizingMaskIntoConstraints = false
    myUIImageView.image = UIImage(named:"pizza.png")
    

    您的方面适合缩放图像现在在UIImageView

    中右对齐
    +----------------------------------+
    |                           [IMAGE]|
    +----------------------------------+
    

    更改约束以在imageview中以不同方式对齐。