CocosCreator 微信分享屏幕截图(IOS+安卓)完整解决方案!

微信分享图片,对缩略图的大小是有要求的,笔者被这个坑的很惨。笔者开发的游戏分辨率为1280*720,安卓缩略图大小为128*72,IOS缩略图大小为256*144.

笔者直接贴代码了,详细的注释代码里面都有的。

JS部分

cc.Class({

    properties: {
        _isCapturing: false, // 正在截图中标志
    },

    // 微信分享屏幕截图
    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); // 保存渲染纹理到图片文件

        // 延时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/MyJsPlugin', 'shareIMG', '(Ljava/lang/String;)V', fullPath);
                } 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);
    },
});

安卓部分

/**
 * 分享图片
 */
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);
}

IOS部分

// 微信分享图片
+ (void) shareIMG:(NSString*)filePath {
    // 初始化WXImageObject对象
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = [NSData dataWithContentsOfFile:filePath];
    
    // 初始化WXMediaMessage对象
    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = imageObject;
    
    // 设置缩略图
    UIImage *thumbImage = [AppController compressIMG:filePath width:256 height:144];
    [message setThumbImage:thumbImage];
    
    // 构造一个Req
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    
    // 调用api接口发送数据到微信
    [WXApi sendReq:req];
}

// 压缩图片到指定大小
+ (UIImage *)compressIMG:(NSString *)filePath width:(int)width height:(int)height {
    // 获取图片
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage imageWithData:imageData];
    
    // 压缩图片
    CGSize newSize = CGSizeMake(width, height);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,(NSInteger)newSize.width, (NSInteger)newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

发表评论