iOS性能优化- 图片优化(圆角设置/拉伸设置)

    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
    }

iOS性能优化- 图片优化(圆角设置/拉伸设置)_第1张图片

iOS性能优化- 图片优化(圆角设置/拉伸设置)_第2张图片

你可能感兴趣的:(swift4.0,#,iOS,优化,#,iOS,绘图,动画,#,iOS,Core,Graphics,制图)