/// 给指定的图片进行拉伸
///
func avatarImage(image: UIImage, size:CGSize) -> UIImage? {
let rect = CGRect(origin: CGPoint(), size: size)
//上下文
/*
* size: 绘图尺寸
*不透明 false (透明)
*屏幕分辨率,默认使用 1.0,图像质量不好; 0 表示当前屏幕分辨率
*/
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
//绘图
image.draw(in: rect)
//取结果
let result = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
return result
}
//MARK:设置圆角半径
func setcornerRadiusImage(image: UIImage, size:CGSize) -> UIImage? {
let rect = CGRect(origin: CGPoint(), size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
//背景 填充
UIColor.red.setFill()
//填充
UIRectFill(rect)
//圆路径
let path = UIBezierPath(ovalIn: rect)
//裁切
path.addClip()
image.draw(in: rect)
//绘制内切的圆形
UIColor.darkGray.setStroke()
//绘制边线
path.lineWidth = 2.0
path.stroke()
//取结果
let result = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
return result
}
import Foundation
import UIKit
extension UIImage {
func crop(_ rect: CGRect) -> UIImage? {
var newRect = rect
newRect.origin.x *= scale
newRect.origin.y *= scale
newRect.size.width *= scale
newRect.size.height *= scale
guard let imageRef = self.cgImage?.cropping(to: newRect) else { return nil }
return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
}
func resize(_ size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: size))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
func scaleToFitAtCenter(size: CGSize) -> UIImage? {
let scaleW_H = size.width / size.height
let selfScaleW_H = self.size.width / self.size.height
if selfScaleW_H > scaleW_H {
let w = self.size.height * scaleW_H
let h = self.size.height
let x = (self.size.width - w) / 2.0
let y: CGFloat = 0
return self.crop(CGRect(x: x, y: y, width: w, height: h))?.resize(size)
} else {
let w = self.size.width
let h = self.size.width / scaleW_H
let x: CGFloat = 0
let y = (self.size.height - h) / 2.0
return self.crop(CGRect(x: x, y: y, width: w, height: h))?.resize(size)
}
}
}