图片实现等比压缩

2018-08-09  本文已影响0人  XC1988
let screenHeight:CGFloat = UIScreen.main.bounds.size.height
let screenWidth:CGFloat = UIScreen.main.bounds.size.width
func useImage(image: UIImage) -> NSData {
    //实现等比例缩放
    let hfactor = image.size.width / screenWidth
    let vfactor = image.size.height / screenHeight
    let factor = fmax(hfactor, vfactor)
    //画布大小
    let newWith: CGFloat = image.size.width / factor
    let newHeigth: CGFloat = image.size.height / factor
    let newSize = CGSize(width: newWith, height: newHeigth)
    UIGraphicsBeginImageContext(newSize)
    image.drawInRect(CGRect(x: 0, y: 0, width: newWith, height: newHeigth))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //图像压缩
    let newImageData = UIImageJPEGRepresentation(newImage, 0.5)
    return newImageData!
}
上一篇下一篇

猜你喜欢

热点阅读