gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
cocos 实现 自绘输入框
- User
cocos 实现 自绘输入框
- Assistant
Cocos 实现自绘输入框需要使用 EditBox 组件和自定义 Shader。
首先创建一个 EditBox 组件,并设置其样式、尺寸和位置。然后创建一个自定义的 Shader,用于渲染输入框背景和描边效果。Shader 需要定义两个 Uniform 变量,分别是输入框尺寸和描边宽度。
Shader 代码:
#ifdef GL_ES precision mediump float; #endif varying vec2 v_texCoord; uniform vec2 u_size; uniform float u_outlineWidth; void main() { vec4 color = vec4(1.0, 1.0, 1.0, 1.0); float radius = 4.0; vec2 size = u_size - 2.0 * vec2(u_outlineWidth, u_outlineWidth); vec2 pos = v_texCoord * size; if (pos.x < radius && pos.y < radius) { if (length(vec2(radius, radius) - pos) > radius) { discard; } } else if (pos.x < radius && pos.y > size.y - radius) { if (length(vec2(radius, size.y - radius) - vec2(pos.x, size.y - pos.y)) > radius) { discard; } } else if (pos.x > size.x - radius && pos.y < radius) { if (length(vec2(size.x - radius, radius) - vec2(size.x - pos.x, pos.y)) > radius) { discard; } } else if (pos.x > size.x - radius && pos.y > size.y - radius) { if (length(vec2(size.x - radius, size.y - radius) - vec2(size.x - pos.x, size.y - pos.y)) > radius) { discard; } } if (pos.x > radius && pos.y > radius && pos.x < size.x - radius && pos.y < size.y - radius) { color = vec4(203.0/255.0, 203.0/255.0, 203.0/255.0, 1.0); } gl_FragColor = color; }在编辑器中设置 EditBox 组件的背景和描边颜色为透明色,然后在代码中获取 EditBox 组件的渲染节点,并设置其 Shader。最后在 update 函数中更新 Shader 的 Uniform 变量,以实现输入框大小和描边宽度的变化。
实现代码:
const {ccclass, property} = cc._decorator; @ccclass export class InputBox extends cc.Component { @property(cc.EditBox) editBox: cc.EditBox = null; private _shader: cc.Shader = null; private _outlineWidth: number = 0.5; start() { this._shader = cc.shaderLab.getGLES2Shader(cc.macro.SHADER_POSITION_TEXTURE_COLOR_LOCAL); this.editBox["_updateBackgroundImage"] = this._updateBackgroundImage.bind(this); this.editBox["_updateState"] = this._updateState.bind(this); } update(dt: number) { this._shader.setUniformFloat("u_outlineWidth", this._outlineWidth); this._shader.setUniformVec2("u_size", this.editBox.node.getContentSize()); } private _updateBackgroundImage(sprite: cc.Sprite) { if (!sprite._sgNode) return; sprite._sgNode.setShaderProgram(this._shader); } private _updateState() { let focused = this.editBox["_editing"]; let backgroundImage = this.editBox["_backgroundImage"]; if (backgroundImage) { let color = focused ? this.editBox["_backgroundFocusColor"] : this.editBox["_backgroundNormalColor"]; color.a = 0; backgroundImage.color = color; } } }在场景中添加一个节点,将 EditBox 组件挂载到该节点上,并将该节点挂载到 InputBox 组件上。在希望使用输入框的场景中使用 InputBox 节点即可。