cocos creator 手机截屏分享二维码 完整写法。小子虽然不才但也讨厌很多人 直接复制别人的博客粘贴到自己上面还不补全。说多了就是泪啊!不说多了上代码。加班写出来的没有优化谅解哈。
1.这里是手机截屏功能
// Learn cc.Class:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.htmlcc.Class({extends: cc.Component,properties: {// foo: {// // ATTRIBUTES:// default: null, // The default value will be used only when the component attaching// // to a node for the first time// type: cc.SpriteFrame, // optional, default is typeof default// serializable: true, // optional, default is true// },// bar: {// get () {// return this._bar;// },// set (value) {// this._bar = value;// }// },_canvas: null,targetNode: cc.Node,camera: cc.Camera},// LIFE-CYCLE CALLBACKS:onLoad() {this.init();},init() {let texture = new cc.RenderTexture();texture.initWithSize(this.targetNode.width, this.targetNode.height, cc.gfx.RB_FMT_S8);this.camera = this.node.addComponent(cc.Camera);this.camera.targetTexture = texture;this.texture = texture;},start() {if (CC_JSB && cc.sys.isNative) {this.camera.enabled = true;this.scheduleOnce(() => {let picData = this.createCaptImage();let name = "LMJL-" + Date.now() + ".png";let filePath = jsb.fileUtils.getWritablePath() + name;//'render_to_sprite_image.png';let success = jsb.saveImageData(picData, this.texture.width, this.texture.height, filePath)if (success) {// var ok = false;// if(cc.sys.platform == cc.sys.OS_IOS){// ok = cc.vv.GLSDKMgr.savePic(picData, name);// }else{// }var ok = cc.vv.GLSDKMgr.savePic(filePath, name);if (ok) cc.vv.GLUtils.showTips("保存完毕");console.log("save image data success, file: " + filePath);}else {console.log("save image data failed!");}this.camera.enabled = false;this.node.removeFromParent();}, 0.5);} else {// h5this.createCanvas();var dataURL = this._canvas.toDataURL("image/png");var img = document.createElement("img");img.src = dataURL;//保存图片this.scheduleOnce(() => {var dataURL = this._canvas.toDataURL("image/png")var a = document.createElement("a")a.href = dataURL;a.download = "image";document.body.appendChild(a);a.click();document.body.removeChild(a);this.node.removeFromParent();}, 0.5);}},// 手机createCaptImage() {let data = this.texture.readPixels();let width = this.texture.width;let height = this.texture.height;let picData = new Uint8Array(width * height * 4);let rowBytes = width * 4;for (let row = 0; row < height; row++) {let srow = height - 1 - row;let start = srow * width * 4;let reStart = row * width * 4;// save the piexls datafor (let i = 0; i < rowBytes; i++) {picData[reStart + i] = data[start + i];}}return picData;},// create the canvas and context, filpY the image DatacreateCanvas() {let width = this.texture.width;let height = this.texture.height;if (!this._canvas) {this._canvas = document.createElement('canvas');this._canvas.width = width;this._canvas.height = height;}else {this.clearCanvas();}let ctx = this._canvas.getContext('2d');this.camera.render();let data = this.texture.readPixels();// write the render datalet rowBytes = width * 4;for (let row = 0; row < height; row++) {let srow = height - 1 - row;let imageData = ctx.createImageData(width, 1);let start = srow * width * 4;for (let i = 0; i < rowBytes; i++) {imageData.data[i] = data[start + i];}ctx.putImageData(imageData, 0, row);}return this._canvas;},// create the img elementinitImage() {// return the type and dataUrlvar dataURL = this._canvas.toDataURL("image/png");var img = document.createElement("img");img.src = dataURL;return img;},// create the canvas and context, filpY the image DatacreateSprite() {let width = this.texture.width;let height = this.texture.height;if (!this._canvas) {this._canvas = document.createElement('canvas');this._canvas.width = width;this._canvas.height = height;} else {this.clearCanvas();}let ctx = this._canvas.getContext('2d');this.camera.render();let data = this.texture.readPixels();// write the render datalet rowBytes = width * 4;for (let row = 0; row < height; row++) {let srow = height - 1 - row;let imageData = ctx.createImageData(width, 1);let start = srow * width * 4;for (let i = 0; i < rowBytes; i++) {imageData.data[i] = data[start + i];}ctx.putImageData(imageData, 0, row);}return this._canvas;},getTargetArea() {let targetPos = this.targetNode.convertToWorldSpaceAR(cc.v2(0, 0))let y = cc.winSize.height - targetPos.y - this.targetNode.height / 2;let x = cc.winSize.width - targetPos.x - this.targetNode.width / 2;return {x,y}},clearCanvas() {let ctx = this._canvas.getContext('2d');ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);}// update (dt) {},
});
2、这里是属于js调oc 与js调android
savePic: function (path_file, name) {if (cc.sys.os == cc.sys.OS_ANDROID) {// var funName = this.setCallBack(cc.vv.GLSDKMgr.wechatLoginCallback, "SavePicCallback");var ret = jsb.reflection.callStaticMethod(this.NATIVE_HELPER, "saveImageToGallery", this.ONE_STRING_TOW_STRING_PARAMS, path_file, name);if (ret == "success") {return true;}} else if (cc.sys.os == cc.sys.OS_IOS) {var ret = jsb.reflection.callStaticMethod("NativeHelper", "saveImageToGallery:", path_file);if (ret=="success") {return true;}}return false;},提示:注意js调oc jsb.reflection.callStaticMethod("NativeHelper", "saveImageToGallery:", path_file);传入参数记得一定要在方法名后面加冒号"saveImageToGallery:"不然会出现找不到xxx方法
3、object-c 的中首先得添加相机权限与提示用的是否开启相机访问相册权限
<key>NSPhotoLibraryUsageDescription</key>
<string>此App需要您的同意才能读取媒体资料库</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>是否允许此APP保存图片到相册?</string>
添加这两句话到
xml文件中
配置相机调用的库文件
这两个库文件加入入上图所示中
好了到了这里你就完成了3/4了
现在来上oc代码
.h中
+ (NSString*) saveImageToGallery:(nonnull NSString*)imgpath;#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>.mm文件中的实现+ (NSString*) saveImageToGallery:(NSString*)imgpath{
// NSArray *imageArray = [imgData componentsSeparatedByString:@","];
// NSData *imageData = [[NSData alloc] initWithBase64EncodedString:imageArray[1] options:NSDataBase64DecodingIgnoreUnknownCharacters];
//
// UIImage *image = [UIImage imageWithData:imageData];// 同步执行修改操作NSError *error = nil;__block NSString *assetId = nil;NSURL *url = [NSURL fileURLWithPath:imgpath];ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];if (author ==ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){//无权限 引导去开启NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];if ([[UIApplication sharedApplication] canOpenURL:url]) {[[UIApplication sharedApplication] openURL:url];}}else{// 1. 存储图片到"相机胶卷"[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{// 新建一个PHAssetCreationRequest对象, 保存图片到"相机胶卷"// 返回PHAsset(图片)的字符串标识PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:url];assetId = createAssetRequest.placeholderForCreatedAsset.localIdentifier;} completionHandler:^(BOOL success, NSError * _Nullable error) {if (error) {NSLog(@"保存图片到相机胶卷中失败");}else{NSLog(@"成功保存图片到相机胶卷中");}}];return @"success";}// [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// //写入图片到相册
// PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// } completionHandler:^(BOOL success, NSError * _Nullable error) {
// NSLog(@"success = %d, error = %@", success, error);
//
// }];// UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
以上内容完整基本就是复制粘贴能用 ,不同地方直接根据自己写法修改