IOS 根据显示的空间尺寸来压缩显示图片尺寸

    //按照显示控件的size来设置重新加载图片的尺寸
    func compresImage(srcImage:UIImage,size:CGSize)->UIImage{
        if size.width >= srcImage.size.width
            && size.height >= srcImage.size.height {
            return srcImage
        }
        var newSize = CGSize.init()
        if srcImage.size.width > srcImage.size.height {
            if size.width < srcImage.size.width {
                newSize.height = size.width * srcImage.size.height / srcImage.size.width;
                newSize.width = size.width;
            }
        } else {
            if size.height < srcImage.size.height {
                newSize.width = size.height * srcImage.size.width / srcImage.size.height;
                newSize.height = size.height;
            }
        }
        UIGraphicsBeginImageContext(newSize)
        srcImage.draw(in: CGRect.init(origin: CGPoint.init(x: 0, y: 0)
                , size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!;
    }

你可能感兴趣的:(IOS 根据显示的空间尺寸来压缩显示图片尺寸)