根据UIImageViewWidth的图像调整UIImageView的大小

时间:2013-10-11 19:57:20

标签: uiimageview ios7 frame

我有一个UIImageView,它是整个屏幕的宽度,高度是400像素。

我正在寻找的最终结果是每个图像都具有完全相同的宽度(屏幕宽度),并调整高度以适应这一点,同时保持其纵横比。

因此,如果图像宽度为400像素,则需要减小到320像素宽,并且图像视图的高度应该调整并变得更加紧密以保持比例。

如果图像宽度为240像素,则需要将其宽度增加到320,并将高度调整为TALLER以保持比率。

我一直在浏览很多帖子,这些帖子似乎都只是指向将内容模式设置为宽高比适合,但这并不像我要找的那样。

任何帮助都会很棒,谢谢!

4 个答案:

答案 0 :(得分:0)

所以看起来我发布之后不久,我查看了故事板,由于某种原因,代码没有覆盖故事板。

如果我在故事板中将其更改为Aspect Fit,它实际上将按照预期的方式运行。

:: face palm ::

答案 1 :(得分:0)

您只需在imageview中将内容模式属性设置为Aspect Fit。

答案 2 :(得分:0)

UIImage *originalImage = [UIImage imageNamed:@"xxx.png"];
    double width = originalImage.size.width;
    double height = originalImage.size.height;
    double apectRatio = width/height;

    //You can mention your own width like 320.0
    double newHeight = [[UIScreen mainScreen] bounds].size.width/ apectRatio;
    self.img.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, newHeight);
    self.img.center = self.view.center;
    self.img.image = originalImage;

答案 3 :(得分:0)

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / image.size.width
        let heightRatio = targetSize.height / image.size.height

        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        }

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }

现在从原始图像中获取已调整大小的图像,就像我这样做:

let image = UIImage(named: "YOUR IMAGE NAME")
let newHeight = (image?.size.height/image?.size.width) * YOUR_UIIMAGE_VIEW_WIDTH
let newSize = CGSize(width: YOUR_UIIMAGE_VIEW_WIDTH, height: newHeight)
let newResizedImage = resizeImage(image: image, targetSize: newSize)

希望,这会有所帮助。