【问题标题】:create random rectangles with random colors without overlapping创建具有随机颜色的随机矩形而不重叠
【发布时间】:2016-02-03 18:12:39
【问题描述】:

如何使用 javascript 在 QML 中创建类似的东西?

实际上我知道如何在 QML 中创建矩形,但想做这样的事情。 QML 画布可以是任何大小,但每当加载 QML 部分时,都会生成多个具有随机大小和颜色的正方形,而不会重叠。当我尝试这样做时,矩形以列表形式生成。 我是一名网络开发人员(面向 ruby​​ on rails),但对此类 javascript 内容不熟悉。任何帮助将不胜感激。

【问题讨论】:

标签: javascript qt qml


【解决方案1】:

正如@ddriver 已经注意到的那样,最简单的决定是遍历所有孩子以找到一个新矩形的房间。

Rectangle {
        id: container
        anchors.fill: parent
        property var items: [];
        Component {
            id: rect
            Rectangle {
                color: Qt.rgba(Math.random(),Math.random(),Math.random(),1);
                border.width: 1
                border.color: "#999"
                width: 50
                height: 50
            }
        }

        Component.onCompleted: {
            var cnt = 50;
            for(var i = 0;i < cnt;i ++) {
                for(var t = 0;t < 10;t ++) {
                    var _x = Math.round(Math.random() * (mainWindow.width - 200));
                    var _y = Math.round(Math.random() * (mainWindow.height - 200));
                    var _width = Math.round(50 + Math.random() * 150);
                    var _height = Math.round(50 + Math.random() * 150);

                    if(checkCoord(_x,_y,_width,_height)) {
                        var item = rect.createObject(container,{ x: _x, y: _y, width: _width, height: _height });
                        container.items.push(item);
                        break;
                    }
                }
            }
        }

        function checkCoord(_x,_y,_width,_height) {
            if(container.items.length === 0)
                return true;
            for(var j = 0;j < container.items.length;j ++) {
                var item = container.children[j];
                if(!(_x > (item.x+item.width) || (_x+_width) < item.x || _y > (item.y+item.height) || (_y+_height) < item.y))
                    return false;
            }
            return true;
        }
    }

是的,这不是那么明智的解决方案,但它仍然可以改进。

【讨论】:

    【解决方案2】:

    如果你想要效率,它会以复杂性为代价——你将不得不使用一些空间划分算法。否则,您可以只生成随机值,直到获得足够的不重叠。

    检查两个矩形是否重叠很简单 - 如果矩形 B 的角都不在矩形 A 内,则它们不重叠。如果角/点的 x 和 y 值分别在矩形的 x 和 width 以及 y 和 height 的范围内,则角/点位于矩形内。

    在 JS 中,Math.random() 会给你一个介于 0 和 1 之间的数字,所以如果你想生成一个随机值,例如 50 和 200 之间,你可以通过 Math.random() * 150 + 50 来实现。

    有一个数组,将初始矩形值添加到其中,然后生成新的矩形值,检查它们是否与数组中已有的值重叠,如果没有 - 也将它们添加到数组中。获得足够的矩形值后,继续创建实际的矩形。由于所有矩形都是正方形,因此每个正方形只能使用 3 个值 - x、y 和大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 2019-01-31
      • 1970-01-01
      • 2022-01-03
      • 2011-05-13
      相关资源
      最近更新 更多