您的位置:首页 > 移动开发 > Swift

UIImageView圆角设置swift

2016-04-27 14:16 621 查看
对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)

效果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: