本文主要介紹了iOS 對view進(jìn)行截圖的示例代碼,分享給大家,具體如下:
需要對WKWebView進(jìn)行截圖,之前用的是下面的方法,高版本的系統(tǒng)是沒有問題的,低版本的卻截到一張白圖
- (UIImage *)convertViewToImage:(UIView *)view{ // 第二個參數(shù)表示是否非透明。如果需要顯示半透明效果,需傳NO,否則YES。第三個參數(shù)就是屏幕密度了 UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.bounds.size.width, view.bounds.size.height * 0.8),YES,[UIScreen mainScreen].scale); [view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image;}
查看了之后發(fā)現(xiàn)是層級有問題,沒有截到最上面的視圖,于是改為下面的方法就行了
- (UIImage*)captureView:(UIView *)theView frame:(CGRect)frame{ UIGraphicsBeginImageContextWithOptions(CGSizeMake(theView.bounds.size.width, theView.bounds.size.height*0.8), YES, [UIScreen mainScreen].scale); CGContextRef context = UIGraphicsGetCurrentContext(); UIImage *img; if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){ for(UIView *subview in theView.subviews){ [subview drawViewHierarchyInRect:subview.bounds afterScreenUpdates:YES]; } img = UIGraphicsGetImageFromCurrentImageContext(); }else{ CGContextSaveGState(context); [theView.layer renderInContext:context]; img = UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext(); return img;}
要注意,frame是不能為空的,而且截的太快的話也會有問題,需要設(shè)置afterScreenUpdates為NO,因?yàn)樵O(shè)置為YES后,這些方法會等在view update結(jié)束在執(zhí)行,如果在update結(jié)束前view被release了,會出現(xiàn)找不到view的問題。另外記得使用UIGraphicsBeginImageContextWithOptions,這樣截取出來的是高清圖。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選