【摆摊分享】 图片/文字 的渐变色的一种实现

支持 SpriteLabel!参数可调!摆地摊的时候学习一波~

效果预览:

如何使用?

cc.Spritecc.Label 添加脚本 ColorAssembler2D

调整颜色 colors 参数即可。

每个点的对应位置如下:

如何实现的呢?

对于 cc.RenderComponent 都有一个 _assembler

只要这个 _assembler 是继承 cc.Assembler2D , 就有一个 updateColor 的方法。

只要依葫芦画瓢,修改一下顶点的颜色值就行了,参考代码如下。

// private _updateColors() {
const cmp = this.getComponent(cc.RenderComponent);
if (!cmp) return;
const _assembler = cmp['_assembler'];
if (!(_assembler instanceof cc['Assembler2D'])) return;
const uintVerts = _assembler._renderData.uintVDatas[0];
if (!uintVerts) return;
const color = this.node.color;
const floatsPerVert = _assembler.floatsPerVert;
const colorOffset = _assembler.colorOffset;
let count = 0;
for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
    uintVerts[i] = (this.colors[count++] || color)['_val'];
}

当然这个方法要在引擎渲染之后再修改才有效。

onEnable() {
    cc.director.once(cc.Director.EVENT_AFTER_DRAW, this._updateColors, this);
}

如果移除了这个组建,还要告诉引擎重新渲染这个颜色。

onDisable() {
    cc.director.off(cc.Director.EVENT_AFTER_DRAW, this._updateColors, this);
    this.node['_renderFlag'] |= cc['RenderFlow'].FLAG_COLOR;
}

以上为白玉无冰使用 Cocos Creator v2.3.3 关于 "图片/文字 的渐变色实现" 的技术分享。如果对你有点帮助,欢迎分享给身边的朋友。


走过路过~求个关注~


视频: https://www.bilibili.com/video/BV1ea4y1v7wU/

完整代码(见readme)
原创文章导航

18赞

赞 

能不能搞一个之设置起始和结束颜色,以及渐变的角度 。感觉这样更实用一些

我写的是直接改顶点数据,一般默认就四个顶点,这些插值是着色器光栅化出来的。

如果说要角度这个,想到的一个方案是用shader去写,根据uv坐标算颜色值,类似之前有人写的扫光效果,改个颜色插值应该可行。

冰冰强!!!!!!

强强~~~~

1赞

必须赞一个

强强!!
学习了

可以分享一份 3.6 以后版本的吗?好多API都没有

欸,用了一段时间,真不错

城管来了,快跑呀