# 在UnityUI中绘制线状统计图2.0

## 在之前的基础上添加横纵坐标

public class MyGraph : MonoBehaviour
{
......
private RectTransform labelX;	//声明一个RectTransform
private RectTransform labelY;	//声明一个RectTransform

private void Awake()
{

//graphContainer = transform.Find("GraphContainer").GetComponent<RectTransform>();
......
//因为之前把模板放在graphContainer之下，如果是设为了预制体，直接声明然后赋值就行，不需要这两句
labelX = graphContainer.Find("labelX").GetComponent<RectTransform>();	//找到X轴的模板
labelY = graphContainer.Find("labelY").GetComponent<RectTransform>();	//找到Y轴的模板
......
}

//private GameObject CreateCircle(Vector2 anchoredPosition){......}
private void ShowGraph(List<int> valueList)
{
......
for (int i = 0; i < valueList.Count; i++)
{
......
//lastPoint = circleGameobject;

RectTransform labelx = Instantiate(labelX);	//声明一个RectTransform，复制并实例化模板
//将新生成的坐标设为graphContainer子物体，这样锚点位于graphContainer左下角(原点)方便计算位置坐标
labelx.SetParent(graphContainer);
labelx.gameObject.SetActive(true);			//显示坐标，因为之前隐藏了模板
labelx.anchoredPosition = new Vector2(xPos, -25);	//设置横坐标位置
labelx.GetComponent<Text>().text = i.ToString();	//设置横坐标显示的数据
}
}
//private void DrawLine(Vector2 pointA, Vector2 pointB){......}
//private float RotateAngle(float x, float y){......}
}


	......
private void ShowGraph(List<int> valueList)
{
......
for (int i = 0; i < valueList.Count; i++){......}

int count = 10;		//这里为y坐标个数
for (int i = 0; i <= count; i++)
{
RectTransform labely = Instantiate(labelY);	//获取模板
labely.SetParent(graphContainer);			//设置父物体
labely.gameObject.SetActive(true);			//显示
float yPos = i * 1f / count;
labely.anchoredPosition = new Vector2(-50f, yPos * graphHeight);	//y轴坐标
labely.GetComponent<Text>().text = Mathf.RoundToInt(yPos * maxValue).ToString();	//显示的值
}
}


public class MyGraph : MonoBehaviour
{
......
private RectTransform lineH;
private RectTransform lineV;
......
private void Awake()
{
......
lineH = graphContainer.Find("LineHorizontal").GetComponent<RectTransform>();
lineV = graphContainer.Find("LineVertical").GetComponent<RectTransform>();
......
}
private void ShowGraph(List<int> valueList)
{
......
for (int i = 0; i < valueList.Count; i++)
{
......
//在横纵坐标后面添加即可，因为位置和坐标点相同
RectTransform lineVertical = Instantiate(lineV);
lineVertical.SetParent(graphContainer, false);
lineVertical.gameObject.SetActive(true);
lineVertical.anchoredPosition = new Vector2(xPos, 0f);
}

int count = 10;
for (int i = 0; i <= count; i++)
{
......
//在横纵坐标后面添加即可，因为位置和坐标点相同
RectTransform lingHorizontal = Instantiate(lineH);
lingHorizontal.SetParent(graphContainer, false);
lingHorizontal.gameObject.SetActive(true);
lingHorizontal.anchoredPosition = new Vector2(-0f, yPos * graphHeight);
}
}
}


https://www.cnblogs.com/AlphaIcarus/p/16128922.html

posted @ 2022-04-10 16:46  AlphaIcarus  阅读(44)  评论(0编辑  收藏  举报