版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gilgamesho/article/details/50962035
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: