// 微信分享屏幕截图
shareScreenshot: function () {
// 网页端不支持
if (cc.sys.isBrowser) {
cc.log('网页端不支持微信分享~');
return;
}
// 正在截图中判断
if (this._isCapturing) {
return;
}
this._isCapturing = true;
// 截图文件判断
var fileName = "shareScreenshot.jpg";
var fullPath = jsb.fileUtils.getWritablePath() + fileName;
if (jsb.fileUtils.isFileExist(fullPath)) {
jsb.fileUtils.removeFile(fullPath);
}
// 截图并保存图片文件
var size = cc.director.getWinSize(); // 获取视图大小
var texture = new cc.RenderTexture(size.width, size.height); // 新建渲染纹理
texture.setPosition(cc.p(size.width / 2, size.height / 2)); // 移动渲染纹理到视图中心
texture.begin(); // 开始渲染
cc.director.getRunningScene().visit(); // 访问当前场景
texture.end(); // 渲染结束
texture.saveToFile(fileName, cc.IMAGE_FORMAT_JPG); // 保存渲染纹理到图片文件
console.log("渲染纹理完成");
// 延时50毫秒,检测截图文件是否存在
// 重复10次这个过程,如果超过10次仍没检测到图片文件,截图失败(超时)
var self = this;
var tryTimes = 0;
var fn = function () {
if (jsb.fileUtils.isFileExist(fullPath)) {
// 调用相应平台微信分享图片方法
if (cc.sys.os === cc.sys.OS_ANDROID) {
jsb.reflection.callStaticMethod('org/cocos2dx/javascript/ShareImage', 'shareIMG', '(Ljava/lang/String;)V', fullPath);
console.log("分享成功!!!");
} else if (cc.sys.os === cc.sys.OS_IOS) {
jsb.reflection.callStaticMethod('AppController', 'shareIMG:', fullPath);
}
self._isCapturing = false;
} else {
tryTimes++;
if (tryTimes > 10) {
self._isCapturing = false;
cc.log('截图失败,超时~');
return;
}
setTimeout(fn, 50);
}
};
setTimeout(fn, 50);
console.log("截图完成!!");
},
安卓部分:
/**
* 分享图片
*/
public static void shareIMG(String path) {
// 初始化WXImageObject对象
Bitmap bmp = BitmapFactory.decodeFile(path);
WXImageObject imgObj = new WXImageObject(bmp);
// 初始化WXMediaMessage对象
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
// 设置缩略图
Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 128, 72, true);
bmp.recycle();
msg.thumbData = Util.bmpToByteArray(thumbBmp, true); // Util工具类在微信官方的范例代码中
// 构造一个Req
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("img"); // transaction字段用于唯一标识一个请求
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
// 调用api接口发送数据到微信
api.sendReq(req);
}