UIGraphicsBeginImageContext - 位图上下文
UIGraphicsBeginImageContext
首先,先來認識一個UIGraphicsBeginImageContext,它會創建一個基于位圖的上下文(context)(默認創建一個透明的位圖上下文),并將其設置為當前上下文。
位圖圖形上下文UIKit是不會負責創建的,所以需要用戶手動創建,并且需要在使用完畢后關閉它。在使用UIKit中系統創建的圖形上下文的時候,我們只能在drawRect:方法中使用,由于位圖圖形上下文是由我們手動創建的,所以可以放到任何方法中調用,此外,這個方法并沒有返回值,如果我們要得到我們創建的圖形上下文只需要在創建上下文之后、關閉之前調用UIGraphicsGetCurrentContext()方法,此時取得的上下文就是我們自己創建的圖形上下文了。
方法聲明如下:
void UIGraphicsBeginImageContext(CGSize size);
參數size為新創建的位圖上下文的大小。它同時是由UIGraphicsGetImageFromCurrentImageContext函數返回的圖形的大小。該函數的功能通UIGraphicsBeginImageContextWithOptions的功能相同,相當于UIGraphicsBeginImageContextWithOptions的opaque的參數為NO,scale因子為1.0.
方法聲明如下:
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
size:同UIGraphicsBeginImageContext
opaque:透明開關,如果圖形完全不同透明,設置為YES以優化位圖的存儲。
scale:縮放因子。?
demo1:根據顏色生成一張圖片
static func colorImage( size : CGSize, color : UIColor ) -> UIImage {// 開啟一個圖形上下文UIGraphicsBeginImageContext(size)// 獲取到這個上下文let context = UIGraphicsGetCurrentContext()// 設置顏色context?.setFillColor(color.cgColor)// 繪制context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))// 獲取到這張圖片let image = UIGraphicsGetImageFromCurrentImageContext()// 關閉UIGraphicsEndImageContext()return image!}
demo2:獲取屏幕截圖
// 獲取屏幕的截圖static func screenImage() -> UIImage {// 獲取到windowlet window = UIApplication.shared.delegate?.window as? UIWindow// 開啟一個圖形上下文UIGraphicsBeginImageContext(UIScreen.main.bounds.size)// 系統截屏方法window?.drawHierarchy(in: UIScreen.main.bounds, afterScreenUpdates: true)// 獲取到這張圖片let image = UIGraphicsGetImageFromCurrentImageContext()// 關閉UIGraphicsEndImageContext()return image!}
demo3:根據view生成圖片
// 根據view生成圖片static func viewImage(view : UIView) -> UIImage {// 開啟一個圖形上下文UIGraphicsBeginImageContext(view.frame.size)// 獲取到這個上下文let context = UIGraphicsGetCurrentContext()// 渲染內容到上下文view.layer.render(in: context!)// 獲取到這張圖片let image = UIGraphicsGetImageFromCurrentImageContext()// 關閉UIGraphicsEndImageContext()return image!}
demo4:直接將圖片切割圓角
// 切割圖片生成圓角func cicleImage() -> UIImage {// 開啟一個圖形上下文UIGraphicsBeginImageContext(size)// 獲取到這個上下文let context = UIGraphicsGetCurrentContext()// 設置圓形context?.addEllipse(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))// 裁剪context?.clip()// 重新繪制self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))// 獲取到這張圖片let image = UIGraphicsGetImageFromCurrentImageContext()// 關閉UIGraphicsEndImageContext()return image!}
?
轉載于:https://www.cnblogs.com/chenjiangxiaoyu/p/7464569.html
總結
以上是生活随笔為你收集整理的UIGraphicsBeginImageContext - 位图上下文的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 培训月嫂多少钱啊?
- 下一篇: 微信网名霸气超拽女生