你有n = 24
盒,宽度w = 28
PX每个。时间可以用h
小时和m
分钟来表示。
本质上,你只是想弄清楚每个盒子的开始和结束,你可以将其转换为像素宽度,并将转换为为百分比。
h + m/60
会给你分数小时。乘以宽度以获得时间的像素位置:(h + m/60)*w
。 (快速完整性检查:1:30应该是1半半宽度,即42像素。)
对于这两个时间都这样做,现在您有start_px
和end_px
。这可以让你计算一个width = end_px - start_px
。
现在你可以转换成百分比:width_percent = width/total_width * 100 = width/(w * n) * 100
因此,最终的公式应该是这样的:
start_px = (start_h + start_m/60)*w
end_px = (end_h + end_m/60)*w
width_percent = (end_px - start_px)/(w * n) * 100
编辑:这里有一个快速和肮脏的Python 2脚本(正是我所掌握的)来运行一些示例。
def find_width(start_h, start_m, end_h, end_m, n, w):
start_px = (start_h + start_m/60.)*w
end_px = (end_h + end_m/60.)*w
width_percent = (end_px - start_px)/(w*n)*100
print "%d:%02d-%d:%02d Spans from %dpx to %dpx, or %.2f%%"%(start_h, start_m, end_h, end_m, start_px, end_px, width_percent)
n = 24 # 24 hours
w = 10 # width of 10, easier to check math
# entire day - should be 240 px or 100%
find_width(0,0, 24,0, n,w)
# half day - should be 50%
find_width(0,0, 12,0, n,w)
# try starting from not-zero
find_width(4,0, 16,0, n,w)
find_width(4,30, 5,30, n,w)
# try non-zero minutes
find_width(4,30, 16,30, n,w)
# try less than an hour
find_width(4,30, 5,00, n,w)
find_width(4,30, 4,45, n,w)
此输出:
0:00-24:00 Spans from 0px to 240px, or 100.00%
0:00-12:00 Spans from 0px to 120px, or 50.00%
4:00-16:00 Spans from 40px to 160px, or 50.00%
4:30-5:30 Spans from 45px to 55px, or 4.17%
4:30-16:30 Spans from 45px to 165px, or 50.00%
4:30-5:00 Spans from 45px to 50px, or 2.08%
4:30-4:45 Spans from 45px to 47px, or 1.04%
我建议使用JavaScript这样的事情 – Derek
如果你只是希望公式我认为这可能是更合适的东西,如“算法”或添加标签“几何”? – whrrgarbl
由于将这样做 – JK36