图片裁剪:
新建UIImage扩展 Image类
/// 裁剪图片
func cropToSize(rect: CGRect) -> UIImage {
var newRect = rect
newRect.origin.x *= self.scale
newRect.origin.y *= self.scale
newRect.size.width *= self.scale
newRect.size.height *= self.scale
let cgimage = self.cgImage?.cropping(to: newRect)
let resultImage = UIImage(cgImage: cgimage!, scale: self.scale, orientation: self.imageOrientation)
return resultImage
}
/// 压缩图片数据-不压尺寸
///
/// - Parameters:
/// - maxLength: 最大长度 maxLength/1024 = kb
/// - Returns:
func compressImageTolength(maxLength: Int) -> Data? {
guard let vData = self.jpegData(compressionQuality: 1) else {
return nil
}
JJPrint("压缩前kb:\(Double((vData.count)/1024))")
if vData.count < maxLength {
return vData
}
var compress:CGFloat = 0.9
guard var data = self.jpegData(compressionQuality: compress) else {
return nil
}
while data.count > maxLength && compress > 0.02 {
JJPrint("压缩比:\(compress)")
compress -= 0.07
data = self.jpegData(compressionQuality: compress)!
}
JJPrint("压缩后kb:\(Double((data.count)/1024))")
return data
}
/// UIColor-->UIImage
func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsGetCurrentContext()
return image!
}
/**
* 重设图片大小
*/
func reSizeImage(reSize:CGSize) -> UIImage {
//UIGraphicsBeginImageContext(reSize);
UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale)
self.draw(in: CGRect(x:0,y:0,width:reSize.width,height:reSize.height))
let reSizeImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return reSizeImage
}
/**
* 等比率缩放
*/
func scaleImage(scaleSize:CGFloat) -> UIImage {
let reSize = CGSize(width:self.size.width * scaleSize,height:self.size.height * scaleSize)
return reSizeImage(reSize: reSize)
}
Over !