swift中的extension(即为扩展):是向已有的一个类、结构体或者枚举添加新功能(实例方法或者类型方法),包括在没有获取源代码的情况下扩展类型的能力。
- 对UIView扩展实现swift中的xib或者storyboard可视化(设置圆角cornerRadius、设置borderWidth等),这样在xib或者storyboard中便可直视控件的相应的属性设置效果,不要要Run之后再去看效果:
extension UIView {
@IBInspectable var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor(cgColor:self.layer.borderColor!)
}
set {
self.layer.borderColor = newValue.cgColor
}
}
var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = true
}
}
}
- 对UIImage的扩展(直接可以用点语法调用扩展的属性和方法即可)
extension UIImage {
var height : CGFloat{return self.size.height}
var width : CGFloat{return self.size.width}
// 压缩图片
func imageCompress(targetWidth:CGFloat) -> UIImage {
let targetHeight = (targetWidth/width)*height
UIGraphicsBeginImageContext(CGSize(width: targetWidth, height: targetHeight))
self.draw(in: CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight))
let newImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
//模糊图片
func blurImage(blurValue:NSNumber) -> UIImage {
let context = CIContext(options: [kCIContextUseSoftwareRenderer: true])
let ciImage = CoreImage.CIImage(image: self)
let blurFilter = CIFilter(name: "CJGaussianBlur")
blurFilter?.setValue(ciImage, forKey: kCIInputImageKey)
blurFilter?.setValue(blurValue, forKey: "inputRadius")
let imageRef = context.createCGImage((blurFilter?.outputImage)!, from: (ciImage?.extent)!)
let newImage = UIImage(cgImage: imageRef!)
return newImage
}
}