UIImageView圆角设置swift

来源:互联网 发布:张孝祥java面试宝典 编辑:程序博客网 时间:2024/05/16 04:22


对UIimage和UIImageView做一个扩展,各自扩展了一个函数如下所示:其作用主要是避免了离屏渲染则cpu的的消耗减小。

如果只有几个的话可以使用layer层的cornerRadius和masksToBounds,毕竟用起来比较方便,如果你的项目中有太多的圆角如果用上面的方法会产生离屏渲染会降低cpu的运行效率,则可以采用下面方法:

import Foundation

import UIKit


extension UIImage {

    func kt_drawRectWithRoundedCorner(radius radius: CGFloat, _ sizetoFit: CGSize) -> UIImage {

        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: sizetoFit)

        

        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)

        CGContextAddPath(UIGraphicsGetCurrentContext(),

                         UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners,

                            cornerRadii: CGSize(width: radius, height: radius)).CGPath)

        CGContextClip(UIGraphicsGetCurrentContext())

        self.drawInRect(rect)

        CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)

        let output = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        

        return output

    } 

    

}

extension UIImageView {


     func kt_addCorner(radius radius: CGFloat) {

        self.image = self.image?.kt_drawRectWithRoundedCorner(radius: radius, self.bounds.size)

    }

}

在Controller中这样设置注意,一定要保障UIimage不为空的情况下调用kt_addCorner

   let imgView1 = UIImageView(frame: CGRect(x: 10, y: 100, width: 100, height: 100))

        imgView1.image = UIImage(named: "1.jpg")

        imgView1.kt_addCorner(radius: 30)

        self.view.addSubview(imgView1)


效果如下



0 0