Cocos3x 解决同时勾选 适配屏幕宽度和 适配屏幕高度导致Widget组件失效的问题

正常项目中使用Widget组件将节点固定到某个位置(左下角)时会出现下面这种情况:

按钮并没有对齐到左下角,这是因为canvas被设置为设计大小了,而不是实际大小。

fit width和fit height同时勾选的时候,需要将Canvas或者UI的父节点设置成真正的全屏

typescript 复制代码
import { _decorator, Component, Node, screen, UITransform, view, Widget } from "cc";
const { ccclass, property } = _decorator;

@ccclass("Adapter")
export class Adapter extends Component {
    start() {
        const { width, height } = screen.windowSize;
        const screenWidth = width / view.getScaleX();
        const screenHeight = height / view.getScaleY();
        this.node.parent.getComponent(UITransform).setContentSize(screenWidth, screenHeight);
        // console.log("调整UI", view.getScaleX(), view.getScaleY(), screenWidth, screenHeight);
        //添加Widget适配
        let widget = this.node.getComponent(Widget);
        if (!widget) {
            widget = this.node.addComponent(Widget);
        }
        widget.left = 30; //留点距离给按钮的动画
        widget.bottom = 25;
    }

    update(deltaTime: number) {}
}

//screenWidth和screenHeight就是游戏内全屏的分辨率,将父节点设为这个大小之后,子节点的widget应该也能根据全屏进行适配了。

DownLoad节点的Widget组件就可以生效了

无论是横屏还是竖屏Widget组件都可以生效了

相关推荐
如竟没有火炬6 分钟前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
WeilinerL12 分钟前
泛前端代码覆盖率探索之路
前端·javascript·测试
嵌入式小李.man19 分钟前
C++第十三篇:继承
开发语言·c++
Bryce李小白25 分钟前
Kotlin Flow 的使用
android·开发语言·kotlin
JNU freshman1 小时前
vue 之 import 的语法
前端·javascript·vue.js
剑亦未配妥1 小时前
Vue 2 响应式系统常见问题与解决方案(包含_demo以下划线开头命名的变量导致响应式丢失问题)
前端·javascript·vue.js
爱吃的强哥1 小时前
Vue2 封装二维码弹窗组件
javascript·vue.js
凉柚ˇ1 小时前
Vue图片压缩方案
前端·javascript·vue.js
jarreyer1 小时前
python离线包安装方法总结
开发语言·python
李辰洋1 小时前
go tools安装
开发语言·后端·golang