iOS效能優化- 圖片優化(圓角設定/拉伸設定)
阿新 • • 發佈:2019-01-24
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.orange
let rect = CGRect.init(x: 0, y: 0, width: 200, height: 200)
let imgV = UIImageView.init(frame: rect)
imgV.center = view.center
view.addSubview(imgV)
guard let img = UIImage.init(named: "avatar_default_big") else {
return
}
imgV.image = optimizationImg(img: img, rect: rect, backColor: view.backgroundColor)
}
/// 圖片優化部分
///
/// - Parameters:
/// - img: 圖片
/// - rect: 拉伸大小
/// - Returns: 返回拉伸好的圖片
private func optimizationImg (img: UIImage, rect: CGRect, backColor: UIColor?) -> UIImage? {
//1. 上下文
//圖片上下文的拉伸size / 設定不透明屬性為true / 設定生成的圖片解析度為當前裝置的解析度(0)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
//1.1 設定多餘背景的顏色同父檢視顏色
backColor?.setFill()
UIRectFill(rect)
//1.2 切出圓角
let path = UIBezierPath.init(ovalIn: rect)
path.addClip()
//2. 繪製 - 新的rect
img.draw(in: rect)
//3. 取得結果
let newImg = UIGraphicsGetImageFromCurrentImageContext()
//4. 關閉上下文
UIGraphicsEndImageContext()
return newImg
}