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组件都可以生效了

相关推荐
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
李少兄1 天前
JavaScript 隐式全局变量解析
javascript
霍霍的袁2 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超2 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int2 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端