0

我正在尝试在没有 ImageView 相互交叉的布局上生成随机 ImageView。我在屏幕尺寸内生成一个随机点,如下所示:

private Point generateRandomLocation(Point dimensions) {
    Random random = new Random();

    // generate random x
    int x = random.nextInt((dimensions.x - 0) + 1);

    // generate random y
    int y = random.nextInt((dimensions.y - 0) + 1);

    Point location = new Point(x, y);

    if(!collision(location)) {
        return new Point(x, y);
    } else {
        return generateRandomLocation(dimensions);
    }

}

碰撞方法包含以下方法来确定 ImageViews 是否碰撞。BubbleImage 是 ImageView 的简单扩展。

private boolean collision(Point location) {
    // takes 100 as inital width & height
    int x_1 = location.x;
    int y_1 = location.y;

    int x_2;
    int y_2;

    boolean collided = false;

    // get all bubbleimages
    for (int i = 0; i < mainLayout.getChildCount(); i++) {
        View childView = mainLayout.getChildAt(i);
        if (childView instanceof BubbleImage) {
            x_2 = (int) childView.getX();
            y_2 = (int) childView.getY();

            // create rectangles
            Rect rect1 = new Rect(x_1, y_1, x_1 + 100, y_1 - 100);
            Rect rect2 = new Rect(x_2, y_2, x_2 + 100, y_2 - 100);
            collided = Rect.intersects(rect1, rect2);

        }
    }

    return collided;

}

有人在这里发现错误的逻辑吗?

编辑: Rect.intersects() 似乎返回 false,即使图像视图相交也是如此。

4

1 回答 1

2

在创建新的 Rects rect1 & rect2 时,构造函数是 Rect(left, top, right, bottom)。例如 Rect(10, 10, 20, 20),因为 android 屏幕原点在左上角。您以错误的方式创建了 Rects,如 Rect(left, bottom , right, top )。尝试在构造函数调用中切换第 2 和第 4 个参数,或者将第 4 个参数增加到大于第 2 个。像这样: Rect rect1 = new Rect(x_1, y_1, x_1 + 100, y_1 + 100);

于 2013-10-25T10:09:12.177 回答