1. 程式人生 > >03 - renderInContext:與drawInContext:方法 - 截圖(截圖)無法顯示子控制元件

03 - renderInContext:與drawInContext:方法 - 截圖(截圖)無法顯示子控制元件

03 - renderInContext:與drawInContext:方法 - 截圖(截圖)無法顯示子控制元件

問題描述

  • 前提 : 自定義View:包含若干個子控制元件
  • 理想現象 : 用上下文(UIGraphics)取得View.layer 生成的圖片,導到對應路徑
  • 報錯reason : 無報錯
  • 解決方式 : 渲染方法從drawInContext:改為renderInContext:

建立部分Code:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 UIGraphicsBeginImageContextWithOptions(self
.drawVIew.bounds.size, NO,0.0); //獲取當前的上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); //把控制器的view的內容畫到上下文當中. [self.drawVIew.layer drawInContext:ctx]; // [self.drawVIew.layer renderInContext:ctx];//修改後 //從上下文當中生成一張圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //關閉上下文
UIGraphicsEndImageContext(); ///Users/apple/Desktop/素材 //把圖片寫入到桌面 //把圖片轉成二進位制流 //NSData *data = UIImageJPEGRepresentation(newImage, 1); NSData *data = UIImagePNGRepresentation(newImage); [data writeToFile:@"/Users/a1/Desktop/newImage.png" atomically:YES]; }

分析:

  • (void)renderInContext:(CGContextRef)ctx; 該方法為渲染view.layer
/* Defines how the edges of the layer are rasterized. For each of the
     * four edges (left, right, bottom, top) if the corresponding bit is
     * set the edge will be antialiased. Typically this property is used to
     * disable antialiasing for edges that abut edges of other layers, to
     * eliminate the seams that would otherwise occur. The default value is
     * for all edges to be antialiased. */  
  • (void)drawInContext:(CGContextRef)ctx; 該方法為渲染UIImage
/* Rendering properties and methods. **/
    /*  Renders the receiver and its sublayers into 'ctx'. This method
     * renders directly from the layer tree. Renders in the coordinate space
     * of the layer.
     * WARNING: currently this method does not implement the full
     * CoreAnimation composition model, use with caution.
     *  */

修改方法:

渲染方法從drawInContext:改為renderInContext: