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

相关推荐
南境十里·墨染春水21 分钟前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
yuanyxh22 分钟前
Mac 软件推荐
前端·javascript·程序员
万少27 分钟前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
JosieBook2 小时前
【数据库】时序预测能力的分级进化:TimechoAI如何让每一类用户都能精准预见未来
java·开发语言·数据库
加号32 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
diving deep2 小时前
脚本速览-python
开发语言·python
一生了无挂3 小时前
Java处理JSON技巧教学(从基础到高阶实战全覆盖)
java·开发语言·json
swordbob3 小时前
Spring 单例 Bean 是线程安全的吗?
java·开发语言
学Linux的语莫3 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫4 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome