1. iOS截屏
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
在webView使用WebGL的情况下,比如cocos2d,会出现截屏无法截取webview的问题;在视频播放的情况下,无法截取视频窗口。只能单独截取再拼接,有办法能直接截屏,麻烦教我一下
2. web-cocos2d截屏
NSString * js = @"cc.director.on(cc.Director.EVENT_AFTER_DRAW,() => {\
var canvas = document.getElementById(\"GameCanvas\");\
var gl = canvas.getContext('experimental-webgl',{preserveDrawingBuffer: true});\
var img = gl.canvas.toDataURL('image/png',0.1);\
cc.director.off(cc.Director.EVENT_AFTER_DRAW);\
var messagebody = {\"img\":img};\
var message = {'message': 'screenShotAction','body': messagebody};\
window.webkit.messageHandlers.ScreenShotHandler.postMessage(JSON.stringify(message));\
});";
生成的img是带一个头部信息的base64数据,通过消息发送出去
[self.gameWebView evaluateJavaScript:js completionHandler:^(id _Nullable rest, NSError * _Nullable error) {
//NSLog(@"screenshot error%@", error);
}];
webView代理接收消息,base64转UIImage
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"ScreenShotHandler"]) {
NSString* msgBodyString = (NSString*)message.body;
NSData *jsonData = [msgBodyString dataUsingEncoding:NSUTF8StringEncoding];
NSError*err;
NSDictionary *msgBody = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
//NSLog(@"screenShot message =%@", msgBody);
NSString* msgName = msgBody[@"message"];
if ([msgName isEqualToString:@"screenShotAction"]) {
NSString *dataStr = msgBody[@"body"][@"img"];
if (dataStr) {
dataStr = [dataStr componentsSeparatedByString:@","].lastObject;
NSData *data = [[NSData alloc] initWithBase64EncodedString:dataStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *img = [UIImage imageWithData:data];
//NSLog(@"screenShot img =%@", img);
}
}
}
}