BITKit/Src/Unity/Scripts/UX/Library/AdaptiveGrid.cs

70 lines
1.9 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Net.BITKit.UX
{
public class AdaptiveGrid : VisualElement
{
public new class UxmlFactory : UxmlFactory<AdaptiveGrid, UxmlTraits>
{
}
public AdaptiveGrid()
{
style.flexDirection = FlexDirection.Row;
style.flexWrap = Wrap.Wrap;
RegisterCallback<GeometryChangedEvent>(_ => UpdateLayout());
RegisterCallback<AttachToPanelEvent>(_ => UpdateLayout());
RegisterCallback<DetachFromPanelEvent>(_ => UpdateLayout());
}
private void UpdateLayout()
{
var width = resolvedStyle.width;
if (childCount == 0 || width <= 0) return;
var sampleVisualElement = contentContainer[0];
var max = sampleVisualElement.resolvedStyle.maxWidth.value;
var min = sampleVisualElement.resolvedStyle.minHeight.value;
if (max == 0)
{
max = sampleVisualElement.resolvedStyle.width;
}
if(min == 0)
{
min = max * 0.8f;
}
var count= Mathf.FloorToInt(width / min);
var remainder = width % count;
var itemWidth = (width - remainder) / count;
var itemHeight = itemWidth * 0.8f;
var spacing = (width - itemWidth * count) / (count - 1);
spacing = spacing < 0 ? 0 : spacing;
for (var i = 0; i < childCount; i++)
{
var child =contentContainer[i];
child.style.width = itemWidth-spacing;
child.style.height = itemHeight-spacing;
if (i % count != 0)
{
child.style.marginRight = spacing;
child.style.marginBottom = spacing;
}
}
}
}
}