你有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