2011-04-08 77 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