いくつかの実験と単体テストの後、私は解決策を見つけたと思います。実際には、幅/高さは必要ありませんが、要素の比率は同じです。
私はレイアウトを表す以下のクラスました:
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;
}
}
を
出典
2016-04-16 09:46:52
J4N