如果不知道egret怎么调用微信小程序API,请看Egret微信小游戏API调用
该章最终效果如下:
一、在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 = 0xF8F8F8;
let avatar: eui.Image = new eui.Image();
avatar.x = 100;
avatar.y = 100;
avatar.width = 120;
avatar.height = 120;
avatar.source = userInfo.avatarUrl;
this.addChild(avatar);
let nickName: eui.Label = new eui.Label();
nickName.x = 100;
nickName.y = 250;
nickName.textColor = 0xff0000;
nickName.text = userInfo.nickName;
this.addChild(nickName);
let shareGroup: eui.Group = new eui.Group();
shareGroup.width = 200;
shareGroup.height = 80;
shareGroup.x = 100;
shareGroup.y = 350;
this.addChild(shareGroup);
let shareLabel: eui.Label = new eui.Label();
shareLabel.text = "share";
shareLabel.addEventListener(egret.TouchEvent.TOUCH_TAP, this.share, this);
shareLabel.left = 0;
shareLabel.top = 0;
shareLabel.bottom = 0;
shareLabel.right = 0;
shareLabel.textColor = 0xffffff;
let shareRect: eui.Rect = new eui.Rect();
shareRect.left = 0;
shareRect.top = 0;
shareRect.bottom = 0;
shareRect.right = 0;
shareRect.fillColor = 0x1097DC;
shareGroup.addChild(shareRect);
shareGroup.addChild(shareLabel);
}
private share() {
console.log("share");
platform.share();
}
当然你在测试的时候需要用一个可以使用的微信小游戏ID,就可以分享发送给朋友。