天天看点

Egret -- Egret 微信小游戏分享(wx.shareAppMessage)

如果不知道egret怎么调用微信小程序API,请看Egret微信小游戏API调用

该章最终效果如下:

Egret -- Egret 微信小游戏分享(wx.shareAppMessage)

一、在platform.ts中新增两个函数share和init

/** 
 * 平台数据接口。
 * 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息
 * 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定
 * 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式
 */
declare interface Platform {
    getUserInfo(): Promise<any>;
    login(): Promise<any>;
    share(): Promise<any>;
    init(): Promise<any>;
}

class DebugPlatform implements Platform {
    async getUserInfo() {
        return { nickName: "username" }
    }
    async login() {
    }
    async share(){
    }
    async init() {
    }
}
if (!window.platform) {
    window.platform = new DebugPlatform();
}
declare let platform: Platform;
declare interface Window {
    platform: Platform
}
           

init()方法是打开微信分享,同时也可以将其他要初始化的操作写入到该函数中。

share() 方法实现分享功能。

二、在platform.js文件中添加两个方法init()和share()

/**
 * 请在白鹭引擎的Main.ts中调用 platform.login() 方法调用至此处。
 */

class WxgamePlatform {

    // 之前的代码***

    init() {
      wx.showShareMenu();
    }

    share() {
      wx.shareAppMessage({
        title: "share test",
        imageUrl: "http://pic.qiantucdn.com/58pic/22/06/55/57b2d98e109c6_1024.jpg!/fw/1024/watermark/url/L2ltYWdlcy93YXRlcm1hcmsvZGF0dS5wbmc=/repeat/true/crop/0x1024a0a0",
        query: ""
      });
    }

    // 之后的代码
}
           

三、我们在main.ts中写一个按钮,点击后调用分享

/**
 * 创建游戏场景
 * Create a game scene
 */
private createGameScene(userInfo: any) {

    let bg: eui.Rect = new eui.Rect();
    this.addChild(bg);
    bg.width = this.stage.width;
    bg.height = this.stage.height;
    bg.fillColor = ;

    let avatar: eui.Image = new eui.Image();
    avatar.x = ;
    avatar.y = ;
    avatar.width = ;
    avatar.height = ;
    avatar.source = userInfo.avatarUrl;
    this.addChild(avatar);

    let nickName: eui.Label = new eui.Label();
    nickName.x = ;
    nickName.y = ;
    nickName.textColor = ;
    nickName.text = userInfo.nickName;
    this.addChild(nickName);

    let shareGroup: eui.Group = new eui.Group();
    shareGroup.width = ;
    shareGroup.height = ;
    shareGroup.x = ;
    shareGroup.y = ;
    this.addChild(shareGroup);

    let shareLabel: eui.Label = new eui.Label();
    shareLabel.text = "share";
    shareLabel.addEventListener(egret.TouchEvent.TOUCH_TAP, this.share, this);
    shareLabel.left = ;
    shareLabel.top = ;
    shareLabel.bottom = ;
    shareLabel.right = ;
    shareLabel.textColor = ;

    let shareRect: eui.Rect = new eui.Rect();
    shareRect.left = ;
    shareRect.top = ;
    shareRect.bottom = ;
    shareRect.right = ;
    shareRect.fillColor = ;

    shareGroup.addChild(shareRect);
    shareGroup.addChild(shareLabel);
}

private share() {
    console.log("share");
    platform.share();
}
           

当然你在测试的时候需要用一个可以使用的微信小游戏ID,就可以分享发送给朋友。

继续阅读