Unity_使用Image和脚本生成虚线段

发布时间:2024年01月24日

生成如图样式的虚线段

原理:使用Image做一条线段,这个方法的原理就是给固定的片元长度,对Image进行分割,把片元添加到一个列表中,然后循环对列表中的偶数位进行隐藏,也可以调整线段的宽度

缺陷:有曲线折线的时候,要对每个片元再做旋转位移等操作,且效果不太理想,所以对直线最方便

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DashLineDraw : MonoBehaviour
{
    public static DashLineDraw _dashlineInstance;
    public Image TargetWellWidth;//井径
    public Image TargetWellPosition;//方位
    public Image TargetWellincline;//井斜

    public int WidthpieceLength,inclineLength;//固定线的片元长度

    private void Awake()
    {
        _dashlineInstance = this;
        WidthpieceLength = 5;
        inclineLength = 10;

        DashLine(TargetWellWidth, WidthpieceLength);
        //DashLine(TargetWellPosition, WidthpieceLength);
        //DashLine(TargetWellincline, inclineLength);
    }
   
    /// <summary>
    /// 画虚线
    /// </summary>
    /// <param name="目标线段"></param>
    /// <param name="片元长度"></param>
    public void DashLine(Image targetpic,int pieceLength)
    {
        int pieceNum;//片元数量
        List<GameObject>pieceList = new List<GameObject>();
        RectTransform targetRect;
        targetRect = targetpic.GetComponent<RectTransform>();

        float offsetLineX = (targetRect.sizeDelta.x) / 2;
        pieceNum = (int)((targetpic.GetComponent<RectTransform>().rect.width) / pieceLength);
        RectTransform firstRectTransform = null;
        
        for (int i = 0; i < pieceNum; i++)
        {
            Image pieceImage = Instantiate(targetpic, transform);
            RectTransform pieceRectTransform = pieceImage.rectTransform;

            if (i == 0)
            {
                pieceRectTransform.sizeDelta = new Vector2(pieceLength, 2);
                pieceRectTransform.anchoredPosition = new Vector2(targetRect.anchoredPosition.x - offsetLineX + (pieceLength / 2), targetRect.anchoredPosition.y);
                firstRectTransform = pieceRectTransform;
            }
            else
            {
                pieceRectTransform.sizeDelta = new Vector2(pieceLength, 2);
                pieceRectTransform.anchoredPosition = new Vector2(firstRectTransform.anchoredPosition.x + (pieceLength * i), firstRectTransform.anchoredPosition.y);
            }
            pieceList.Add(pieceImage.gameObject);
        }
        targetpic.GetComponent<Image>().enabled = false;
        for (int i = 0; i < pieceList.Count; i++)
        {
            if ((i + 1) % 2 == 0)
            {
                // 偶数
                pieceList[i].GetComponent<Image>().enabled = false;
            }
        }
    }
}

通过调整Length对宽度调整。

文章来源:https://blog.csdn.net/leikang111/article/details/135827721
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。