python - 查找由具有 x、y、w、h 像素坐标的矩形覆盖的图 block 的坐标

标签 python algorithm math geometry coordinates

假设我有一个使用 16x16 像素的基于图 block 的系统。您将如何找出由浮点像素单元定义的矩形覆盖了哪些图 block ?

例如,

rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)

我能可靠地做到这一点的唯一方法是使用循环。有没有更好的办法?除以 16 给出了边缘情况的错误答案。这是我在 python 中使用的一些示例代码:

#!/usr/bin/env python

import math

TILE_W = 16
TILE_H = 16

def get_tile(x,y,w,h):
    t_x = int(x / TILE_W)
    t_x2 = t_x
    while t_x2*TILE_W < (x+w):
        t_x2 += 1
    t_w = t_x2-t_x

    t_y = int( y / TILE_H)
    t_y2 = t_y
    while t_y2*TILE_H < (y+h):
        t_y2 += 1
    t_h = t_y2-t_y

    return t_x,t_y,t_w,t_h

(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)

(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)

(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)

(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)

(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)

(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)

(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)

(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)

最佳答案

Matt 的错误修复解决方案:

from __future__ import division
import math

TILE_W = TILE_H = 16

def get_tile(x,y,w,h):
    x1 = int(math.floor(x/TILE_W))
    x2 = int(math.ceil((x + w)/TILE_W))
    y1 = int(math.floor(y/TILE_H))
    y2 = int(math.ceil((y + h)/TILE_H))
    return x1, y1, x2-x1, y2-y1

关于python - 查找由具有 x、y、w、h 像素坐标的矩形覆盖的图 block 的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1108929/

相关文章:

algorithm - 如何获得这样的特定序列?

python - 在 Python 中创建网格

algorithm - 最长非递减数组的递归分而治之算法

c++ - 您所知道的最快的 Dijkstra 实现是什么(在 C++ 中)?

Javascript:计算给定中心点和另一个点的圆的半径

c# System.OverflowException 异常

python - 带有 fastcgi 的 lighttpd 上的 Flask 不提供 CSS 和图像

python - 如何获取正在使用的TOR入口节点的IP地址

python - 如何在特殊情况下提取两个关键字之间的子字符串?

c++ - 如何在 C 或 C++ 的 O(n) 中删除数组中的重复元素?