使用Aspect Fit对齐UIImageView

问题描述 投票:70回答:11

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

iphone cocoa-touch interface-builder
11个回答
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

0
投票

如果你需要实现aspectFit并摆脱空白空间

别忘了从故事板中删除imageview的宽度约束并享受

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

-4
投票

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

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

您的方面适合缩放图像现在在UIImageView中右对齐

+----------------------------------+
|                           [IMAGE]|
+----------------------------------+

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


30
投票

如果使用Storyboard,这可以通过约束来实现......

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


9
投票

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

但这是一个解决方法:

首先需要通过计算尺寸明确地调整源图像的大小(如果它与UIImageViewcontentMode = .scaleAspectFit中)。

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属性,就可以在原始图像上调用此函数。此外,请确保在此处(甚至在界面生成器中)设置imageView所需的contentMode

let image = UIImage(named: "MySourceImage")
imageView.image = image?.aspectFitImage(inRect: imageView.frame)
imageView.contentMode = .left

8
投票

尝试设置:

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

这对我有用。


3
投票

由于开发人员的缘故,我使用了UIImageViewAligned来改变图像的对齐方式

UIImageViewAligned


2
投票

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

  1. 我应用了视网膜4形状因子(Editor-> Apply Retina 4 Form Factor)。
  2. 我固定了高度和宽度。

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

希望这可以帮助。


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];

希望这可以帮助。


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)])

0
投票

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

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

这导致图像视图的框架被调整为精确地适合图像,因此纵横比适合工作,并且图像视图框架属性正在进行繁重的工作,将图像视图放在应该达到相同效果的位置。

这是我使用的一些代码:

首先,我发现它一般非常有用,是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
© www.soinside.com 2019 - 2024. All rights reserved.