Swift-UIImage Extension

根據(jù)color和size生成新的圖片

extension UIImage {
     public class func image(color: UIColor, size: CGSize) -> UIImage? {
        if size.width <= 0 || size.height <= 0 {
            return nil
        }
        
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
}

根據(jù)radius,corners,borderWidth,borderColor,borderLineJoin生成新的圖片

extension UIImage {

      public func image(radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor) -> UIImage? {
        return image(radius: radius, corners: UIRectCorner.allCorners, borderWidth: borderWidth, borderColor: borderColor, borderLineJoin: .miter)
    }

      public func image(radius: CGFloat, corners: UIRectCorner, borderWidth: CGFloat, borderColor: UIColor, borderLineJoin: CGLineJoin) -> UIImage? {
        /*
         /* Line join styles. */
         
         public enum CGLineJoin : Int32 {
         
         case miter
         
         case round
         
         case bevel
         }
         */
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context?.scaleBy(x: 1, y: -1)
        context?.translateBy(x: 0, y: -rect.size.height)
        
        let minSize = min(size.width, size.height)
        if borderWidth < minSize / 2 {
            let path = UIBezierPath.init(roundedRect: rect.insetBy(dx: borderWidth, dy: borderWidth), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: borderWidth))
            path.close()
            
            context?.saveGState()
            path.addClip()
            context?.draw(cgImage!, in: rect)
            context?.restoreGState()
        }
        
        if borderWidth > 0 && borderWidth < minSize / 2 {
            let strokeInset = (floor(borderWidth*scale)+0.5) / scale
            let strokeRect = rect.insetBy(dx: strokeInset, dy: strokeInset)
            let strokeRadius = radius > scale / 2 ? radius-scale/2 : 0
            
            let path = UIBezierPath.init(roundedRect: strokeRect, byRoundingCorners: corners, cornerRadii: CGSize(width: strokeRadius, height: borderWidth))
            path.close()
            
            path.lineWidth = borderWidth
            path.lineJoinStyle = borderLineJoin
            borderColor.setStroke()
            path.stroke()
        }
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
}

圖片壓縮

extension UIImage {
      public func compressed(quality: CGFloat = 0.5) -> UIImage? {
        guard let data = compressedData(quality: quality) else { return nil }
        return UIImage(data: data)
    }
    
    public func compressedData(quality: CGFloat = 0.5) -> Data? {
        return UIImageJPEGRepresentation(self, quality)
    }
}

圖片縮放

extension UIImage {
     public func scaled(toHeight: CGFloat, opaque: Bool = false, with orientation: UIImageOrientation? = nil) -> UIImage? {
        let scale = toHeight / size.height
        let newWidth = size.width * scale
        UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, scale)
        draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    public func scaled(toWidth: CGFloat, opaque: Bool = false, with orientation: UIImageOrientation? = nil) -> UIImage? {
        let scale = toWidth / size.width
        let newHeight = size.height * scale
        UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, scale)
        draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

圓角圖片

extension UIImage {
     public func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
        let maxRadius = min(size.width, size.height) / 2
        let cornerRadius: CGFloat
        if let radius = radius, radius > 0 && radius <= maxRadius {
            cornerRadius = radius
        } else {
            cornerRadius = maxRadius
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        let rect = CGRect(origin: .zero, size: size)
        UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
        draw(in: rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

初始化方法

extension UIImage {
     //init with color and size
     public convenience init(color: UIColor, size: CGSize) {
        UIGraphicsBeginImageContextWithOptions(size, false, 1)
        color.setFill()
        UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            self.init()
            return
        }
        UIGraphicsEndImageContext()
        guard let aCgImage = image.cgImage else {
            self.init()
            return
        }
        self.init(cgImage: aCgImage)
    }
    
    // simplified contentsOfFile: method
    public convenience init(fileNamed: String) {
        let path = UIImage.createLocalUrl(forImageNamed: fileNamed)?.path
        self.init(contentsOfFile: path!)!
    }
    
    static func createLocalUrl(forImageNamed name: String) -> URL? {
        
        let fileManager = FileManager.default
        let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
        if name.contains(".jpg") {
            return cacheDirectory.appendingPathComponent(name)
        }
        let scale = UIScreen.main.scale
        var scaleName = ""
        switch scale {
        case 2:
            scaleName = name + "@2x.png"
        case 3:
            scaleName = name + "@3x.png"
        default:
            scaleName = name + ".png"
        }
        let url = cacheDirectory.appendingPathComponent("\(scaleName)")
        
        guard fileManager.fileExists(atPath: url.path) else {
            guard
                let image = UIImage(named: name),
                let data = UIImagePNGRepresentation(image)
                else { return nil }
            
            fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
            return url
        }
        
        return url
    }
}

資源來自網(wǎng)絡(luò)和日常整理论皆,持續(xù)更新

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末畅哑,一起剝皮案震驚了整個濱河市到千,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖芙委,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绣张,死亡現(xiàn)場離奇詭異,居然都是意外死亡绎狭,警方通過查閱死者的電腦和手機(jī)细溅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來儡嘶,“玉大人喇聊,你說我怎么就攤上這事”目瘢” “怎么了誓篱?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵邻耕,是天一觀的道長氨淌。 經(jīng)常有香客問我俺陋,道長秃流,這世上最難降的妖魔是什么盆顾? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任丰榴,我火速辦了婚禮者祖,結(jié)果婚禮上缴川,老公的妹妹穿的比我還像新娘厕诡。我一直安慰自己党远,他們只是感情好削解,可當(dāng)我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著沟娱,像睡著了一般氛驮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上济似,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天矫废,我揣著相機(jī)與錄音,去河邊找鬼砰蠢。 笑死蓖扑,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的台舱。 我是一名探鬼主播律杠,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼竞惋!你這毒婦竟也來了柜去?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤拆宛,失蹤者是張志新(化名)和其女友劉穎嗓奢,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體胰挑,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡蔓罚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了瞻颂。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片豺谈。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖贡这,靈堂內(nèi)的尸體忽然破棺而出茬末,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布丽惭,位于F島的核電站击奶,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏责掏。R本人自食惡果不足惜柜砾,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望换衬。 院中可真熱鬧痰驱,春花似錦、人聲如沸瞳浦。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽叫潦。三九已至蝇完,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間矗蕊,已是汗流浹背短蜕。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留拔妥,地道東北人忿危。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像没龙,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子缎玫,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容