Swift 开发中类库扩展

诸子百家

平时开发我们都希望能写出更简单高效的代码。下面是平时开发使用到的扩展。仅供参考。

UIView

extension UIView{
    var width: CGFloat {
        get {
            return self.frame.size.width
        }
        
        set {
            self.frame.size.width = newValue
        }
    }
    
    var height: CGFloat {
        get {
            return self.frame.size.height
        }
        
        set {
            self.frame.size.height = newValue
        }
    }
    
    var size: CGSize {
        get {
            return self.frame.size
        }
        
        set {
            self.frame.size = newValue
        }
    }
    
    var origin: CGPoint {
        get {
            return self.frame.origin
        }
        set {
            self.frame.origin = newValue
        }
    }
    
    var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        
        set {
            self.frame.origin.x = newValue
        }
    }
    
    var y: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    
    var centerX: CGFloat {
        get {
            return self.center.x
        }
        set {
            self.center.x = newValue
        }
    }
    
    var centerY: CGFloat {
        get {
            return self.center.y
        }
        set {
            self.center.y = newValue
        }
    }
    
    var left: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame.origin.x = newValue
        }
    }
    
    var right: CGFloat {
        get {
            return self.frame.origin.x + self.frame.size.width
        }
        set {
         self.frame.origin.x = newValue - self.frame.size.width
        }
    }
    
    var top: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    var bottom: CGFloat {
        get {
            return self.frame.origin.y + self.frame.size.height
        }
        set {
            self.frame.origin.y = newValue - self.frame.size.height
        }
    }
    
    func setAnchorPointTo(point: CGPoint) {
        self.frame = self.frame.offsetBy(dx: (point.x - self.layer.anchorPoint.x) * self.frame.size.width, dy: (point.y - self.layer.anchorPoint.y) * self.frame.size.height);
        
        self.layer.anchorPoint = point;
    }
}
UIImage

import UIKit
import Accelerate

extension UIImage {
    
    /// EZSE: Returns Image size in Bytes
    public func getSizeAsBytes() -> Int {
        return UIImageJPEGRepresentation(self, 1)?.count ?? 0
    }
    
    /// EZSE: Returns Image size in Kylobites
    public func getSizeAsKilobytes() -> Int {
        let sizeAsBytes = getSizeAsBytes()
        return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0
    }
    
    /**
     *  获得一个原始的图片
     */
    class func originImage(name: String) -> UIImage? {
        return (UIImage(named: name)?.withRenderingMode(.alwaysOriginal))!
    }
    
    /// 根据颜色生成一张指定大小的图片
    class func imageWithColor(color: UIColor) -> UIImage? {
        // 描述矩形
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        
        // 开启位图上下文
        UIGraphicsBeginImageContext(rect.size)
        // 获取位图上下文
        let context: CGContext? = UIGraphicsGetCurrentContext()
        // 使用color填充上下文
        context?.setFillColor(color.cgColor)
        // 渲染下上问
        context?.fill(rect)
        // 从上下文获取图片
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        // 结束上下文
        UIGraphicsEndImageContext()
        
        return theImage
    }
    
    /// 拉伸图片到指定尺寸
    class func compressImage(imgSrc: UIImage, toSize: CGSize) -> UIImage? {
        // 定义cgrect
        let rect = CGRect(x: 0, y: 0, width: toSize.width, height: toSize.height)
        UIGraphicsBeginImageContext(toSize)
        imgSrc.draw(in: rect)
        let compressedImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return compressedImg
    }
    
    /// 指定位置获取像素点平铺拉伸图片
    class func strechImageWithName(imageName: String) -> UIImage? {
        let image = UIImage(named: imageName)
        
        return image?.stretchableImage(withLeftCapWidth: Int((image?.size.width)! * 0.5), topCapHeight:Int((image?.size.height)! * 0.5))
    }
    
    class func strechImage(name: String, posX: CGFloat, posY: CGFloat) -> UIImage? {
        let image = UIImage(named: name)
        
        return image?.stretchableImage(withLeftCapWidth: Int((image?.size.width)! * posX), topCapHeight:Int((image?.size.height)! * posY))
    }
    
    /// 截屏
    class func screenShot() -> UIImage? {
        let imageSize = UIScreen.main.bounds.size
        
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        
        let context = UIGraphicsGetCurrentContext()
        
        for window in UIApplication.shared.windows {
            if window.screen == UIScreen.main {
                context?.saveGState()
                context?.translateBy(x: window.center.x, y: window.center.y)
                context?.concatenate(window.transform)
                context?.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
                window.layer.render(in: context!)
                
                context?.restoreGState()
            }
        }
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image
    }
    
    /// 添加水印
    class func addImage(image: UIImage, maskImage: UIImage, maskFrame pos: CGRect) -> UIImage? {
        UIGraphicsBeginImageContext(image.size)
        
        image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        
        // 水印图片的位置
        maskImage.draw(in: pos)
        
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return resultImage
    }
    
    /// 高斯模糊-----coreImage
    class func coreBlurImage(image: UIImage, blur: CGFloat) -> UIImage? {
        // 上下文
        let context = CIContext(options: nil)
        let inputImage = CIImage(cgImage: image.cgImage!)
        // 设置filter
        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(inputImage, forKey: kCIInputImageKey)
        filter?.setValue(blur, forKey: "inputRadius")
        // 模糊图片
        let result = filter?.value(forKey: kCIOutputImageKey) as! CIImage
        let outImage = context.createCGImage(result, from: result.extent)
        let blurImage = UIImage(cgImage: outImage!)
        
        return blurImage
    }
    
    /// 创建毛玻璃效果背景ImageView
    class func createFrost(img: UIImage, toView: UIView) -> UIImageView? {
        let w = toView.frame.size.width
        let h = toView.frame.size.height
        
        let blurImageView = UIImageView(frame: CGRect(x: -w / 2, y: -h / 2, width: 2 * w, height: 2 * h))
        blurImageView.contentMode = .scaleAspectFill
        blurImageView.image = img
        
        // 创建毛玻璃
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) as UIVisualEffectView
        visualEffectView.frame = blurImageView.frame
        
        // 添加毛玻璃
        blurImageView.addSubview(visualEffectView)
        
        return blurImageView
    }
    
    /// 高斯模糊---vImage
    class func gaussianBlur(image: UIImage, blurAmount: inout CGFloat) -> UIImage? {
        // 高斯模糊参数(0 -- 1)之间, 超出范围强行转为0.5
        if blurAmount > 1.0 || blurAmount < 0.0 {
            blurAmount = 0.5
        }
        
        var boxSize = Int(blurAmount * 40)
        boxSize = boxSize - (boxSize % 2) + 1
        
        let img = image.cgImage
        
        var inBuffer = vImage_Buffer()
        var outBuffer = vImage_Buffer()
        
        let inProvider =  img!.dataProvider
        let inBitmapData =  inProvider!.data
        
        inBuffer.width = vImagePixelCount(img!.width)
        inBuffer.height = vImagePixelCount(img!.height)
        inBuffer.rowBytes = img!.bytesPerRow
        inBuffer.data = UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(inBitmapData))
        
        // 手动申请内存
        let pixelBuffer = malloc(img!.bytesPerRow * img!.height)
        
        outBuffer.width = vImagePixelCount(img!.width)
        outBuffer.height = vImagePixelCount(img!.height)
        outBuffer.rowBytes = img!.bytesPerRow
        inBuffer.data = pixelBuffer
        
        var error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0), UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend))
        
        if (kvImageNoError != error)
        {
            error = vImageBoxConvolve_ARGB8888(&inBuffer,
                                               &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0),
                                               UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend))
            if (kvImageNoError != error)
            {
                error = vImageBoxConvolve_ARGB8888(&inBuffer,
                                                   &outBuffer, nil, vImagePixelCount(0), vImagePixelCount(0),
                                                   UInt32(boxSize), UInt32(boxSize), nil, vImage_Flags(kvImageEdgeExtend))
            }
         }
        
        let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
        
        let ctx = CGContext(data: outBuffer.data,
                            width: Int(outBuffer.width),
                            height: Int(outBuffer.height),
                            bitsPerComponent: 8,
                            bytesPerRow: outBuffer.rowBytes,
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
    
        let imageRef = ctx!.makeImage()
        
        //手动申请内存
        free(pixelBuffer)
    
        return UIImage(cgImage: imageRef!)
    }

}
UIColor

extension UIColor {
    
    public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
    }
    
    public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
        var formatted = hexString.replacingOccurrences(of: "0x", with: "")
        formatted = formatted.replacingOccurrences(of: "#", with: "")
        if let hex = Int(formatted, radix: 16) {
            let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
            let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
            let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
            self.init(red: red, green: green, blue: blue, alpha: alpha)
        } else {
            return nil
        }
    }
    
    
    public convenience init(gray: CGFloat, alpha: CGFloat = 1) {
        self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha)
    }
    
    
    public var redComponent: Int {
        var r: CGFloat = 0
        getRed(&r, green: nil, blue: nil, alpha: nil)
        return Int(r * 255)
    }
    
    
    public var greenComponent: Int {
        var g: CGFloat = 0
        getRed(nil, green: &g, blue: nil, alpha: nil)
        return Int(g * 255)
    }
    
    
    public var blueComponent: Int {
        var b: CGFloat = 0
        getRed(nil, green: nil, blue: &b, alpha: nil)
        return Int(b * 255)
    }
    
    
    public var alpha: CGFloat {
        var a: CGFloat = 0
        getRed(nil, green: nil, blue: nil, alpha: &a)
        return a
    }
    
    
    public static func randomColor(randomAlpha: Bool = false) -> UIColor {
        let randomRed = CGFloat.random()
        let randomGreen = CGFloat.random()
        let randomBlue = CGFloat.random()
        let alpha = randomAlpha ? CGFloat.random() : 1.0
        return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha)
    }
    
}

private extension CGFloat {
    static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
        return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower
    }
}
NSObject

// 根据文件名称初始化

extension NSObject {
    public func fromClassName(className: String) -> NSObject {
        let className = Bundle.main.infoDictionary?["CFBundleName"] as! String + "." + className
        let aClass = NSClassFromString(className) as! UIViewController.Type
        
        return aClass.init()
    }
}
CGRect

extension CGRect {
    
    public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
        self.init(x: x, y: y, width: w, height: h)
    }
    
    public var x: CGFloat {
        get {
            return self.origin.x
        }
        set(value) {
            self.origin.x = value
        }
    }
    
    public var y: CGFloat {
        get {
            return self.origin.y
        }
        set(value) {
            self.origin.y = value
        }
    }
    
    public var w: CGFloat {
        get {
            return self.size.width
        }
        set(value) {
            self.size.width = value
        }
    }
    
    public var h: CGFloat {
        get {
            return self.size.height
        }
        set(value) {
            self.size.height = value
        }
    }
}

你可能感兴趣的:(Swift 开发中类库扩展)