ExtJS 5:在加载的图像上调整面板大小

ExtJS 5: Resize panel on image loaded

本文关键字:调整 图像 加载 ExtJS      更新时间:2023-09-26

这似乎是一项微不足道的任务,但我仍然无法完成。我正在用ExtJS 5构建一个应用程序,我有一个面板,上面有一个图像组件。面板必须将(shrinkWrap : true)调整为图像的原始大小。问题是,当布局管理器计算面板的大小时,图像尚未完全加载,因此其大小为0,0。我尝试添加不同的侦听器,如afterrenderrenderboxready,以及几乎所有其他侦听器,但似乎对我无效——图像大小始终等于0。我还尝试绑定这两个组件的大小,正如您将在下面的代码中看到的那样,但这也不起作用。如果我将boxready事件配置为延迟1秒,则最终会计算图像大小,并且我可以调用updateLayout(),但这是一个非常不可靠的解决方案,因为图像是从远程服务器加载的,我无法预测服务器响应的确切时间。我知道,在应用程序生命周期的某个时刻,图像会被加载,我需要找到正在触发的事件,以便调整面板的大小。

示例代码

Ext.application({   name   : 'MyApp',
    launch : function() {
        /* 
         * I was hoping that taking the image out of the panel 
         * will 'force' it to be created earlier.
         */
        var img = Ext.create('Ext.Img', {
            src : 'img.jpg',
            reference : 'bgimg',
            publishes : {
                width : true,
                height: true
            }
            listeners : {
                boxready : { fn : 'imgReady', scope : this, delay : 100 }
            }
        });
        Ext.create('Ext.Panel', {
            renderTo : Ext.get('extjs-content'),
            width : 1000,
            height: 700,
            defaults : {
                border : true
            },
            layout : 'border',
            items : [{
                region : 'north',
                height : 80,
            }, {
                region : 'east',
                width : 200,
                collapsible : true
            }, {
                region : 'center',
                autoScroll : true,
                items : [{
                    /*
                     * This is the container of the image. Please note that
                     * I need it to preserve its absolute layout.
                     */
                    id : 'canvas',
                    layout : 'absolute',
                    shrinkWrap : true,
//                  bind : {
//                      width : '{bgimg.width}',
//                      height: '{bgimg.height}'
//                  },
                    items : [img]
                }]
            }]
        });
    },
    /*
     * If I call this with delay of 1000ms the image size is 'ready'
     * otherwise it is 0, 0.
     */
    imgReady : function(img) {
        console.log('Image size: %o', img.getSize());
        Ext.ComponentQuery.query('#canvas')[0].updateLayout();
    }
});

您可以跟踪图像何时加载img元素的load事件。

var img = Ext.create('Ext.Img', {
        src : 'img.jpg',
        reference : 'bgimg',
        publishes : {
            width : true,
            height: true
        },
        listeners : {
            load : {
               element : 'el',
               fn : 'imgReady'
            }
        }
    });