将UIImage调整为UIImageView

Nan*_*noc 6 uiimageview ios

我试图将图像放入uiimageview,图像下载并加载dinamically,并且只有一个分辨率可用于ios和Android应用程序.

因此,我需要图像来保持纵横比和比例宽度,我将UIImageView内容模式设置为 UIViewContentModeScaleAspectFill,但它将图像居中,因此它会从屏幕上移出顶部和底部,图像将被设计为底部是不必要的.

如何将图像对齐左上角?

并且UIImageView能为我扩展到宽度吗?或者我该怎么办?

提前致谢.

编辑:

我尝试过setcliptobounds将图像剪切为图像视图大小,这不是我的问题.

UIViewContentModeTopLeft工作得很好,但现在我无法申请UIViewContentModeScaleAspectFill,或者我可以申请两者吗?

Mox*_*oxy 12

您可以缩放图像以适合图像视图的宽度.

您可以使用类别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
Run Code Online (Sandbox Code Playgroud)

这样您就可以使用它来缩放图像

UIImage *scaledImage = [originalImage scaleToWidth:myImageView.frame.size.width];
myImageView.contentMode = UIViewContentModeTopLeft;
myImageView.image = scaledImage;
Run Code Online (Sandbox Code Playgroud)