ios – 如何在Swift中调整图像大小?

前端之家收集整理的这篇文章主要介绍了ios – 如何在Swift中调整图像大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用iOS的应用程序,使用 Swift和Parse.com

我试图让用户从图像选择器中选择图片,然后将所选图像的大小调整为200×200像素,然后再上传到我的后端.

Parse.com有一个名为“AnyPic”的Instagram复制应用程序的教程,它提供了用于调整图像大小的代码,但它在Objective-C ….

// Resize the image to be square (what is shown in the preview)
UIImage *resizedImage = [anImage resizedImageWithContentMode:UIViewContentModeScaleAspectFit
        bounds:CGSizeMake(560.0f,560.0f)
        interpolationQuality:kCGInterpolationHigh];
// Create a thumbnail and add a corner radius for use in table views
UIImage *thumbnailImage = [anImage thumbnailImage:86.0f
        transparentBorder:0.0f
        cornerRadius:10.0f
        interpolationQuality:kCGInterpolationDefault];

如何在Swift中创建所选图片(然后上传)的200x200px版本?

而且,缩略图功能在做什么?

解决方法

swift中的图像大小调整功能如下.
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 = CGSizeMake(size.width * heightRatio,size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,size.height * widthRatio)
    }

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

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

    return newImage
}

使用上述功能,并用200 * 200调整图像大小如下代码

self.resizeImage(UIImage(named: "yourImageName")!,targetSize: CGSizeMake(200.0,200.0))

查看我的博文,Resize image in swift and objective C,了解更多细节.

swift3已更新

func resizeImage(image: UIImage,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,1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

猜你在找的iOS相关文章