将UIImage调整为UIImageView



我正在尝试将一个图像放入uiimageview,这些图像通常是下载和加载的,只有一种分辨率可用于ios和android应用程序。

因此,我需要图像保持纵横比和比例宽度,我将UIImageView内容模式设置为UIViewContentModeScaleAspectFill,但它以图像为中心,因此无论是顶部还是底部,它都会离开屏幕,图像将被设计为不需要底部。

如何将图像与左上角对齐?

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

提前谢谢。

编辑:

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

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

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

您可以在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的超类的UIView具有属性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.

您不能同时与UIImageView对齐并保持纵横比,但是UIImageView有一个名为UIImageViewAligned的很棒的子类,这对您来说是可能的。你可以在github上找到这个项目
你需要做的如下:

  1. 首先将标题和实现从UIImageViewAligned master/UIImageViewAligned/复制到您的项目
  2. 将IB中对象库中的ImageView对象插入到视图中
  3. 在"实用程序"窗格的"标识检查器"中将ImageView的类更改为UIImageViewAligned
  4. 然后在Identity Inspector的"用户定义的运行时属性"部分添加所需的对齐方式作为关键路径

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

最新更新