unity利用Image畫直線,以及折線圖
阿新 • • 發佈:2019-01-07
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// 掛載在parent上 /// </summary> public class DrawLine : MonoBehaviour { public Image image;//直線素材 給個紅顏色用於識別 public Vector2 rectA;//指的是rectTransform.anchoredPosition;直線起點 public Vector2 rectB;//直線終點 public Button button;//畫直線按鈕 public RectTransform point;//輔助顯示起點終點位置的小圓形,實際是一張Image,圓形圖片給個黃色用於識別 public RectTransform parent;//直線的父物體 // Use this for initialization void Start () { Debug.Log(GetComponent<RectTransform>().anchoredPosition); button.onClick.AddListener(DrawLineClick); } //劃線功能 void DrawLineClick() { DrawStraightLine(rectA, rectB, image.rectTransform, point,transform); } //劃線功能 void DrawStraightLine(Vector2 a,Vector2 b, RectTransform prefab,RectTransform point,Transform parent) { if (a != b) { GameObject point1 = Instantiate(point.gameObject, parent); GameObject point2 = Instantiate(point.gameObject, parent); point1.SetActive(true); point2.SetActive(true); point1.GetComponent<RectTransform>().anchoredPosition = a; point2.GetComponent<RectTransform>().anchoredPosition = b; float distance = Vector2.Distance(a, b);//計算起點終點兩點距離 float angle = Vector2.SignedAngle(a - b, Vector2.left);//求夾角 計算起點終點的向量和 Vector2.left的夾角 GameObject go = Instantiate(image.gameObject, parent);//克隆預設進行劃線 go.gameObject.SetActive(true); go.GetComponent<RectTransform>().anchoredPosition = (a + b) / 2; go.GetComponent<RectTransform>().sizeDelta = new Vector2(distance, 5); go.transform.localRotation = Quaternion.AngleAxis(-angle, Vector3.forward); Debug.Log("distance:" + distance + " angle:" + angle + " imagePos:" + image.rectTransform.anchoredPosition); } } // Update is called once per frame void Update () { } }
折線圖連結: https://pan.baidu.com/s/1FdqujmCFx5fuU9dAFQ44PA 提取碼: 4d6y 複製這段內容後開啟百度網盤手機App,操作更方便哦