Ios 将UIImage调整为UIImageView

Ios 将UIImage调整为UIImageView,ios,uiimageview,Ios,Uiimageview,我正试图在uiimageview中安装一个图像,图像是通过友好方式下载和加载的,ios和android应用程序只有一种分辨率 因此,我需要图像保持纵横比和缩放宽度,我将UIImageViewcontent模式设置为 UIViewContentModeScaleAspectFill,但它将图像居中,因此顶部和底部的图像都不在屏幕上,图像的设计将使底部不再需要 如何将图像与左上角对齐 我也能按宽度缩放图像吗?或者我该怎么做 提前谢谢 编辑: 我尝试了setcliptobounds,这将图像剪切为im

我正试图在uiimageview中安装一个图像,图像是通过友好方式下载和加载的,ios和android应用程序只有一种分辨率

因此,我需要图像保持纵横比和缩放宽度,我将
UIImageView
content模式设置为
UIViewContentModeScaleAspectFill
,但它将图像居中,因此顶部和底部的图像都不在屏幕上,图像的设计将使底部不再需要

如何将图像与左上角对齐

我也能按宽度缩放图像吗?或者我该怎么做

提前谢谢

编辑:

我尝试了
setcliptobounds
,这将图像剪切为imageview大小,这不是我的问题


UIViewContentModeTopLeft
运行良好,但现在我无法应用
uiviewContentModeScaleSpectFill
,或者我可以同时应用两者吗?

UIView
UIImageView
的超类,它有一个属性
contentMode
。 对于图像的左上对齐,可以使用以下常量

UIViewContentModeTopLeft

Aligns the content in the top-left corner of the view.
保持纵横比

UIViewContentModeScaleAspectFit

Scales the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

可以缩放图像以适应图像视图的宽度

您可以在
UIImage
上使用一个类别来创建具有选定宽度的新图像

@interface UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width;

@end

@implementation UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width
{
    UIImage *scaledImage = self;
    if (self.size.width != width) {
        CGFloat height = floorf(self.size.height * (width / self.size.width));
        CGSize size = CGSizeMake(width, height)

        // Create an image context
        UIGraphicsBeginImageContext(size);

        // Draw the scaled image
        [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

        // Create a new image from context
        scaledImage = UIGraphicsGetImageFromCurrentImageContext();

        // Pop the current context from the stack
        UIGraphicsEndImageContext();
    }
    // Return the new scaled image
    return scaledImage;
}

@end
这样,您可以使用它来缩放图像

UIImage *scaledImage = [originalImage scaleToWidth:myImageView.frame.size.width];
myImageView.contentMode = UIViewContentModeTopLeft;
myImageView.image = scaledImage;

您不能同时使用UIImageView对齐和保留纵横比,但是UIImageView有一个名为UIImageViewAligned的很好的子类,使这一点成为可能。您可以在github上从找到此项目。
您需要做的事情如下:

  • 首先将UIImageViewAligned master/UIImageViewAligned/中的标题和实现复制到项目中
  • 将IB中对象库中的ImageView对象插入视图
  • 在“实用程序”窗格中,在Identity Inspector中将ImageView的类更改为UIImageViewAligned
  • 然后在Identity Inspector的“用户定义的运行时属性”部分中添加所需的对齐方式作为关键路径

  • 就这样。运行您的项目以确保它。

    可能重复使用UIViewContentModetoLeft使用此[imageView setClipsToBounds:YES];很好,第一个问题解决了,那么我如何将图像缩放到UIImageView宽度?如果要保持纵横比,就不能这样做。为什么不通过image.size.width来获得图像宽度;并使用此选项更改UIImageView的宽度。这样你就不必拉伸图像了。图像将比屏幕大。这是缩放宽度而不是高度,我需要保持纵横比。我误解了你想要实现的目标。我编辑了-scaleToWidth:,现在应该是正确的