unity利用Image画直线,以及折线图

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/1kRAs4JWHvTOd43HxQKI-wQ 提取码: 4icb 复制这段内容后打开百度网盘手机App,操作更方便哦

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值