1. 程式人生 > 其它 >UnityUI繪製柱狀統計圖

UnityUI繪製柱狀統計圖

柱狀統計圖可以線上狀統計圖的基礎上進行修改

線狀統計圖在這裡:https://www.cnblogs.com/AlphaIcarus/p/16123434.html

MyGraph中新增新方法來畫出柱狀圖

private GameObject CreateBar(Vector2 pos, float width)
    {
        GameObject gameObject = new GameObject("bar", typeof(Image));
        gameObject.transform.SetParent(graphContainer, false);
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();

        rectTransform.anchoredPosition = new Vector2(pos.x, 0f);
        rectTransform.sizeDelta = new Vector2(width, pos.y);
        rectTransform.anchorMin = new Vector2(0, 0);
        rectTransform.anchorMax = new Vector2(0, 0);
        return gameObject;
    }

然後修改ShowGraph方法

private void ShowGraph(List<int> valueList)
    {
        ......
        for (int i = 0; i < valueList.Count; i++)
        {
            float xPos = i * xSpace;
            float yPos = ySpace * valueList[i];
            
            //新增一個畫柱狀圖的方法即可
            CreateBar(new Vector2(xPos, yPos), xSpace * 0.5f);
            
            //暫時註釋掉線狀圖的方法
            /*GameObject dotGameobject = CreateDot(new Vector2(xPos, yPos));
            if (lastPoint != null)
            {
                DrawLine(lastPoint.GetComponent<RectTransform>().anchoredPosition, dotGameobject.GetComponent<RectTransform>().anchoredPosition);
            }
            lastPoint = dotGameobject;*/
            ......
        }
        ......
    }

顯示結果:

這個問題是因為圖片的錨點位於中心
可以將柱狀圖片的錨點設為底部中心,或者上移圖片,增加y 座標

這裡我重新設定圖片的錨點
return前新增一句即可
rectTransform.pivot = new Vector2(0.5f, 0f);
顯示效果:

最後可以將畫線狀圖和柱狀圖分別設為兩個方法,然後通過UI的選擇來呼叫