[英]Calculate how many elements will fit on image when spaces are involved
我需要渲染N
項目,這些項目的寬度為x
像素,它們之間的間距為N-1
個y
像素。
我需要計算屏幕上將觸發多少項。 我正在做的是將振幅數組呈現為列。 這是我沒有空格的測試產品:
我首先計算適合的項目數量,然后對原始數組進行重新采樣以獲取確切的適合屏幕的值數量。 這與每列5像素相同,您可以看到原始數組已被重新采樣:
我現在使用的公式是no_items = Math.floor(canvasWidth/(barWidth+spaceWidth))
:
/**
* Recalculates waveform data for given width of canvas
* @param {number} canvasWidth Image width in pixels
* @param {number} barWidth Width of waveform bars
* @param {number} spaceWidth Width of spaces between bars
* @returns {Uint8Array} recalculated bytes
*/
recalculateForWidth(canvasWidth, barWidth, spaceWidth) {
const no_items = Math.floor(canvasWidth/(barWidth+spaceWidth))
const result = new Uint8Array(no_items);
// Resampling code follows
...
return result;
}
但這顯然假設數據末尾有一個額外的空格-它只是簡單地計算出項目寬度為條形寬度+空格寬度。
我想渲染的末尾沒有空格的條形圖,那么如何計算有多少空格就可以容納空格卻又沒有空格呢?
為了簡化,讓我們舉一個小例子。 假設您有103個像素,並且您希望條形圖寬5個像素,並且它們之間的間隔為2個像素。 如您所說,條形比空格多1個。 您希望最后一個欄位於屏幕的末尾,因此請將寬度減小此數量,即98px。
然后,將其余的寬度除以成對的bar-space,每對的總長度為barWidth + spaceWidth。 也就是說,您有98/7 = 14對。 總共有15個酒吧。
因此,您的公式應為
(canvasWidth - barWidth) / (barWidth + spaceWidth) + 1
最后的+1是最后一個小節的位置。
希望能為您修復它。
您的總寬度為:
barWidth(NumberBars) + spaceWidth(NumberBars - 1) = TotalWidth
擴展為:
barWidth(NumberBars) + (spaceWidth)(NumberBars) - spaceWidth = TotalWidth
在兩側增加spaceWidth:
barWidth(NumberBars) + spaceWidth(NumberBars) = TotalWidth + spaceWidth
因素左側:
NumberBars(barWidth + spaceWidth) = TotalWidth + spaceWidth
並划分:
NumberBars = (TotalWidth + spaceWidth) / (barWidth + spaceWidth)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.