iOS 对view进行截图的示例代码
本文主要介绍了iOS对view进行截图的示例代码,分享给大家,具体如下:
需要对WKWebView进行截图,之前用的是下面的方法,高版本的系统是没有问题的,低版本的却截到一张白图
-(UIImage*)convertViewToImage:(UIView*)view{ //第二个参数表示是否非透明。如果需要显示半透明效果,需传NO,否则YES。第三个参数就是屏幕密度了 UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.bounds.size.width,view.bounds.size.height*0.8),YES,[UIScreenmainScreen].scale); [view.layerrenderInContext:UIGraphicsGetCurrentContext()]; UIImage*image=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); returnimage; }
查看了之后发现是层级有问题,没有截到最上面的视图,于是改为下面的方法就行了
-(UIImage*)captureView:(UIView*)theViewframe:(CGRect)frame{ UIGraphicsBeginImageContextWithOptions(CGSizeMake(theView.bounds.size.width,theView.bounds.size.height*0.8),YES,[UIScreenmainScreen].scale); CGContextRefcontext=UIGraphicsGetCurrentContext(); UIImage*img; if([[[UIDevicecurrentDevice]systemVersion]floatValue]>=7.0){ for(UIView*subviewintheView.subviews){ [subviewdrawViewHierarchyInRect:subview.boundsafterScreenUpdates:YES]; } img=UIGraphicsGetImageFromCurrentImageContext(); }else{ CGContextSaveGState(context); [theView.layerrenderInContext:context]; img=UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext(); returnimg; }
要注意,frame是不能为空的,而且截的太快的话也会有问题,需要设置afterScreenUpdates为NO,因为设置为YES后,这些方法会等在viewupdate结束在执行,如果在update结束前view被release了,会出现找不到view的问题。另外记得使用UIGraphicsBeginImageContextWithOptions,这样截取出来的是高清图。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。