XCharts-Team / XCharts

A charting and data visualization library for Unity. Unity数据可视化图表插件。
https://xcharts-team.github.io
MIT License
3.14k stars 549 forks source link

LineChart.Init() resizes Rectransform after creating background #323

Open XanderV-2158642 opened 1 week ago

XanderV-2158642 commented 1 week ago

When creating a chart that is a child object of a canvas, the chart background fills the size of the but then resizes the to fit the chart. The Background does not get resized resulting in a chart like this: BuggedBackground

This is the code I used when the bug occurs:

//create a simple chart
GameObject go = new GameObject("LineChart");
//Scale the chart like the canvas
go.transform.SetParent(canvas.transform);
RectTransform rtf = go.AddComponent<RectTransform>();
go.transform.localScale = new Vector3(1, 1, 1);

SetupChart(go, "LineChart");
AddData(go.GetComponent<LineChart>());

private void SetupChart(GameObject gameObject, string title )
{
    var chart = gameObject.GetComponent<LineChart>();
    if (chart == null)
    {
        chart = gameObject.AddComponent<LineChart>();
        chart.Init();
    }

    chart.EnsureChartComponent<Title>().show = true;
    chart.EnsureChartComponent<Title>().text = title;

    chart.EnsureChartComponent<Tooltip>().show = true;
    chart.EnsureChartComponent<Legend>().show = false;

    var xAxis = chart.EnsureChartComponent<XAxis>();
    var yAxis = chart.EnsureChartComponent<YAxis>();
    xAxis.show = true;
    yAxis.show = true;
    xAxis.type = Axis.AxisType.Time;
    yAxis.type = Axis.AxisType.Value;

    xAxis.splitNumber = 10;
    xAxis.boundaryGap = true;
}

private void AddData(LineChart chart)
{
    chart.RemoveData();
    chart.AddSerie<Line>();
    chart.AddSerie<Line>();
    for (int i = 0; i < 20; i++)
    {
        chart.AddXAxisData("x" + i);
        chart.AddData(0, Random.Range(10, 20));
        chart.AddData(1, Random.Range(10, 20));
    }
    chart.RefreshChart();
    chart.RefreshAllComponent();
}

This code comes from the examples folder here, but is divided in smaller functions for my purposes.

When adding rtf.sizeDelta = new Vector2(580, 300); to the first part:

//create a simple chart
GameObject go = new GameObject("LineChart");
//Scale the chart like the cnavas
go.transform.SetParent(canvas.transform);
RectTransform rtf = go.AddComponent<RectTransform>();
go.transform.localScale = new Vector3(1, 1, 1);
rtf.sizeDelta = new Vector2(580, 300);

The background is fully filled. Another workaround is disabling the background component.

Another thing I couldn't wrap my head around was that the background did fill the whole chart when changing a parameter of the chart (e.g. anchoring) at runtime in the unity scene editor. Doing this in scripts did not change the background.

Im using Unity editor v:2022.3.35f1 x-charts version: 3.11.1

monitor1394 commented 6 days ago

Thank you for your feedback, this issue has been fixed in the master branch.