最近在處理一個(gè)屏幕截圖的crash的時(shí)候厕鹃,遇到一些問(wèn)題,看了很多關(guān)于屏幕截圖的方法乍丈,這里結(jié)合crash說(shuō)下屏幕截圖剂碴。
看了很多截屏的方法,如下兩個(gè)最為簡(jiǎn)單明了:
- 使用系統(tǒng)自帶的snapshotViewAfterScreenUpdates:方法轻专,參數(shù)為YES忆矛,代表視圖的屬性改變渲染完畢后截屏,參數(shù)為NO代表立刻將當(dāng)前狀態(tài)的視圖截圖
UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
UISwitch *sw = [UISwitch new];
[showView addSubview:sw];
showView.backgroundColor = [UIColor redColor];
[self.view addSubview:showView];
UIView *snap1 = [showView snapshotViewAfterScreenUpdates:YES];
self.snapView = snap1;
snap1.center = self.view.center;
[self.view addSubview:snap1];
效果圖:
Snip20160126_2.png
2请垛、得到截圖的圖片
特別說(shuō)明:renderInContext:方法在iOS8上會(huì)偶爾崩潰催训,這也是我遇到的問(wèn)題洽议,當(dāng)時(shí)換了各種手段和方案,最后使用drawViewHierarchyInRect:afterScreenUpdates:才解決掉這個(gè)Crash漫拭,希望大家若是遇到了同樣的坑的話能夠幫上一點(diǎn)小忙
UIGraphicsBeginImageContextWithOptions(TOP_VIEW.frame.size, NO, [[UIScreen mainScreen] scale]);
// [TOP_VIEW.layer renderInContext:UIGraphicsGetCurrentContext()]; // 此方法绞铃,除卻iOS8以外其他系統(tǒng)都OK
[TOP_VIEW drawViewHierarchyInRect:TOP_VIEW.bounds afterScreenUpdates:NO];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshot;