南锋

南奔万里空,脱死锋镝余

cocosCreator动态生成二维码

cocosCreator 版本:3.7.2
开发语言:typeScript

我们在游戏开发中,经常会生成一个专属于玩家个人的二维码,比如说推广、充值等功能。

接到这个任务,在网上找了下,还是有很多教程的。但是这些教程大部分都是用QRCode二维码生成库,将js文件设置成插件的形式。然后用画图组件Graphics把二维码画出来。

我这里也是用的同样的思路,但是没有用插件的形式。下面说说具体的方法:

新建工程

打开cocosCreator,创建一个新工程。在scene中添加一个精灵节点,将精灵设置为白色。再在精灵上添加一个Graphics节点。如下图:
示意图

注意:这里要设置要精灵和绘图节点的尺寸,最好是2的倍数,而且建议将Graphics的锚点设置为(0,0)

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
   import { _decorator, Component, Node,Graphics, Color, UITransform } from 'cc';
import { QRCode } from './qr/QRCode';
const { ccclass, property } = _decorator;
let QRErrorCorrectLevel = {
L: 1,
M: 0,
Q: 3,
H: 2
};
@ccclass('qrCode')
export class qrCode extends Component {
@property(Graphics)
graphics:Graphics = null;
start() {
this.qrCode("https://lengmo714.top");
}

private qrCode(url) {
let node = this.graphics;
var qrcode = new QRCode(-1, QRErrorCorrectLevel.H);
qrcode.addData(url);
qrcode.make();

var ctx = node.getComponent(Graphics)!;
ctx.fillColor = Color.BLACK;
var tileW = node.getComponent(UITransform)!.width / qrcode.getModuleCount();
var tileH = node.getComponent(UITransform)!.height / qrcode.getModuleCount();

// draw in the Graphics
for (var row = 0; row < qrcode.getModuleCount(); row++) {
for (var col = 0; col < qrcode.getModuleCount(); col++) {
if (qrcode.isDark(row, col)) {
var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
ctx.rect(Math.round(col * tileW), Math.round(row * tileH), w, h);
ctx.fill();
} else {
// ctx.fillColor = cc.Color.WHITE;
}
var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
}
}
}
}

注意,这里还是要用到画二维码的插件库,只是我没有用这个插件库,qrcode.js代码转成了ts代码。

qrcode.js文件下载地址
完整demo下载地址,ts版本
完整demo下载地址2,ts版本

+