2016-04-16 11 views
0

私はいくつかの要素をレイアウトしたいWPFカスタムパネルを持っています(私の場合は12ですが、理想的には、すべて最小幅/高さが同じです。レイアウトはグリッドですが、必要な列数/行数を選択できます。与えられたサイズに最適なレイアウト(グリッド)を見つける

ウィンドウの比率に応じて、作成する行数と作成する行数を決定する方法を知りたいと思います。

サブエレメントの比率が1/1の場合は、より簡単です。可能なレイアウトの比率を計算する必要があります(私は12のサブエレメント:12/1、6/2、4/3、3/4、2/6、1/12を認めています)パネルの幅/高さの比に近くなります。

私の実際のケースでは、サブアイテムを2倍の幅に設定することができたので、これを計算する方法は少し分かりません。私は彼らの「理想的な大きさ」を取ってから数学をやる必要があると思いますが、どうやってそれを知ることはできません。

ありがとうございました!

答えて

0

いくつかの実験と単体テストの後、私は解決策を見つけたと思います。実際には、幅/高さは必要ありませんが、要素の比率は同じです。

私はレイアウトを表す以下のクラスました:

public class Layout : IEquatable<Layout> 
{ 
    public int RowCount { get; } 
    public int ColumnCount { get; } 
    public double Ratio { get; } 

    public Layout(int rowCount, int columnCount) 
    { 
     RowCount = rowCount; 
     ColumnCount = columnCount; 
     Ratio = (float)rowCount/columnCount; 
    } 
} 

をそして、私は最高のレイアウトを取得するには、次のやった:

public class LayoutAdapter 
{ 
    public Layout ComputeBestGridLayout(int elementsCount, double elementRatio, double panelRatio) 
    { 
     IEnumerable<Layout> possibleLayouts = GetPossibleLayouts(elementsCount); 
     return FindBestLayouts(possibleLayouts, elementRatio, panelRatio); 
    } 

    private IEnumerable<Layout> GetPossibleLayouts(int elementCounts) 
    { 
     //TODO Increment "elementsCounts", because maybe with some hole we will have a better match for the ratio 
     List<Layout> acceptedResults =new List<Layout>(); 
     for (int i1 = 0; i1 <= elementCounts; i1++) 
     { 
      double rest2 = elementCounts%((double) i1); 
      if (rest2 == 0) 
      { 
       int i2 = elementCounts/i1; 
       acceptedResults.Add(new Layout(i1,i2)); 
      } 
     } 
     return acceptedResults; 
    } 


    private Layout FindBestLayouts(IEnumerable<Layout> possibleLayouts, double elementRatio, double panelRatio) 
    { 
     Layout closestLayout = null; 
     double minDiff=Double.MaxValue; 


     foreach (Layout possibleLayout in possibleLayouts) 
     { 
      double currentDiff = Math.Abs((panelRatio/ elementRatio) - possibleLayout.Ratio); 
      if (currentDiff < minDiff) 
      { 
       minDiff = currentDiff; 
       closestLayout = possibleLayout; 
      } 
     } 
     return closestLayout; 
    } 

} 
関連する問題