2011-04-08 80 views
1

我正在用Haskell編寫一個簡單的OpenGL遊戲。每當用戶調整窗口大小時,我都會獲得它們的寬度和高度。我需要計算出適合窗戶的最大寬度和高度,同時保持1.6的W/H比率。找到長寬比的最佳方法

這就是我寫的。它可以工作,但我認爲這不是在Haskell中實現它的最好方式。有人建議一些替代方案:

keepRatio (w,h) | w > expectedWidth = (floor expectedWidth, h) 
       | otherwise   = (w, floor(fromIntegral w/fixedRatio)) 
       where expectedWidth = fromIntegral h * fixedRatio 

回答

4

我會用一個後衛(條件)做比率與最接近的像素。

1

試試這個:

keepRatio (w,h) = min sizeByWidth sizeByHeight 
    where sizeByWidth = (w, (w * 5) `div` 8) 
     sizeByHeight = ((h*8) `div` 5, h) 

這是假設你只需要方面

fixedRatio = 1.6 

keepRatio (w,h) = head [(floor w',floor h') | w' <- [w, h*fixedRatio], h' <- [h, w/fixedRatio], w' <= w, h' <= h, w'/h' == fixedRatio ] 
+0

在這種情況下,我們可以說'min'而不是'minBy(比較fst)'嗎? – dave4420 2011-04-09 00:31:25

+0

是的!我忘記了那個例子(Ord a,Ord b)=> Ord(a,b)。據此編輯。 – 2011-04-09 09:52:09