unity 动态加载image以及button,实现image在屏幕内移动

unity  动态加载image以及button,实现image在屏幕内移动、

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class GUI_Test : MonoBehaviour
{
    private static byte[] getImageByte(string imagePath)
    {
        //读取到文件
        FileStream files = new FileStream(imagePath, FileMode.Open);
        //新建比特流对象
        byte[] imgByte = new byte[files.Length];
        //将文件写入对应比特流对象
        files.Read(imgByte, 0, imgByte.Length);
        //关闭文件
        files.Close();
        //返回比特流的值
        return imgByte;
    }
    private List GetImagePath()
    {
        List filePaths = new List();
        string imgtype = "*.JPG|*.PNG";
        string[] ImageType = imgtype.Split('|');
        for (int i = 0; i < ImageType.Length; i++)
        {
           
           string path2 = System.Environment.CurrentDirectory + @"/Assets/Resources/Texture";
            //  string   path06 = "jar:file://" + Application.persistentDataPath + "!/assets/Texture";
            string[] dirs = Directory.GetFiles(path2, ImageType[i]);
            //string[] dirs = Directory.GetFiles(Application.dataPath + @"/Texture", ImageType[i]);
            for (int j = 0; j < dirs.Length; j++)
            {
                filePaths.Add(dirs[j]);
               // Debug.Log("图片路径为     " + dirs[j]);
            }
           // Debug.Log("一共读取到" + dirs.Length + "张图片");
        }
        return filePaths;
    }

    List loadTexture = new List();
    List loadsprite = new List();


    //加载图片
    private void LoadTexture2Sprite()
    {
        //清空一下,防止爆满
        loadTexture.Clear();
        loadsprite.Clear();
        //获取到路径
        List filePaths = new List();


        filePaths = GetImagePath();
        //新建时要给上大小,小于原先的图片大小会出现图片值截取一块的情况

        //根据读取到的文件路径,一个文件一个文件的将图片存储进去
        for (int i = 0; i < filePaths.Count; i++)
        {
            Texture2D t2d = new Texture2D(200, 200);
            //根据路劲读取字节流再转换成图片形式
            t2d.LoadImage(getImageByte(filePaths[i]));
            //放到集合里面
            loadTexture.Add(t2d);
            //将Texture创建成Sprite 参数分别为图片源文件,Rect值给出起始点和大小 以及锚点的位置
            Sprite sprite = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), Vector2.zero);
            //放入集合
            loadsprite.Add(sprite);

        }
    }
    private Rect rect;
    CanvasScaler canvaScaler;

    void Awake()
    {
        canvaScaler = GetComponent();
        rect = new Rect(-Screen.width / 2, -Screen.height / 2, Screen.width, Screen.height);
        float scale = canvaScaler.matchWidthOrHeight == 1 ? canvaScaler.referenceResolution.y / (float)Screen.height : canvaScaler.referenceResolution.x / (float)Screen.width;
        Debug.Log(canvaScaler.matchWidthOrHeight);
        rect = new Rect(rect.x , rect.y , rect.width , rect.height );
    }
    /// 注意rect中心点在中间
    public static bool SetUIArea(Transform target, Rect area, Transform canvas)
    {
        Bounds bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(canvas, target);
        
        if (null == area)
        {
            return false;
        }

        Vector3 delta = default(Vector2);
        if (bounds.center.x - bounds.extents.x < area.x)//target超出area的左边框
        {
            delta.x += Mathf.Abs(bounds.center.x - bounds.extents.x - area.x);
        }
        else if (bounds.center.x + bounds.extents.x > area.width / 2)//target超出area的右边框
        {
            delta.x -= Mathf.Abs(bounds.center.x + bounds.extents.x - area.width / 2);
        }

        if (bounds.center.y - bounds.extents.y < area.y)//target超出area上边框
        {
            delta.y += Mathf.Abs(bounds.center.y - bounds.extents.y - area.y);
        }
        else if (bounds.center.y + bounds.extents.y > area.height / 2)//target超出area的下边框
        {
            delta.y -= Mathf.Abs(bounds.center.y + bounds.extents.y - area.height / 2);
        }

        //加上偏移位置算出在屏幕内的坐标
      //  target.anchoredPosition += delta;
        target.position += delta;
        return delta != default(Vector3);
    }
    private void Update()
    {
       
     SetUIArea(go.transform, rect, transform);
        //Vector3 screen3dPos = Camera.main.WorldToScreenPoint(go.transform.position);
        //Debug.Log(screen3dPos.x);
        //if (screen3dPos.x > Screen.width)
        //{
        //    Debug.Log("in screen");
        //}
        //else
        //{

        //    Debug.Log("out of screen");
        //}
    }

    GameObject go;
    private void Start()
    {
        LoadTexture2Sprite();
        go = new GameObject("image");
      //  go.AddComponent();
        //go = GameObject.CreatePrimitive(PrimitiveType.Plane);
        go.transform.SetParent(this.transform);
        go.AddComponent().sprite = loadsprite[showIamgeIs];
        go.transform.position = new Vector2(350,365);

       // Bounds bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(transform, go.transform);
    }
    private int showIamgeIs = 0;
    private void OnGUI()
    {
        //  Vector3 p = Camera.main.WorldToViewportPoint(go.GetComponent().position);
        if (GUI.Button(new Rect(193, 393, 130, 80), "坐"))
        {
            Debug.Log(go.transform.position.x);
            go.GetComponent().position = new Vector3(
                  go.transform.position.x - 30, go.transform.position.y);
        }
        if (GUI.Button(new Rect(452, 393, 130, 80), "右"))
        {
            go.GetComponent().position = new Vector3(
            go.transform.position.x + 30, go.transform.position.y);
        }
        if (GUI.Button(new Rect(323, 329, 130, 80), "上"))
        {
            go.GetComponent().position = new Vector3(
            go.transform.position.x, go.transform.position.y + 30);
        }
        if (GUI.Button(new Rect(323, 455, 130, 80), "下"))
        {
            go.GetComponent().position = new Vector3(
            go.transform.position.x, go.transform.position.y - 30);
        }
        if (GUI.Button(new Rect(650, 455, 130, 80), "下一张"))
        {
            showIamgeIs++;
            if (showIamgeIs <= loadsprite.Count - 1)
            {
                for (int i = 0; i < loadsprite.Count; i++)
                {

                    go.GetComponent().sprite = loadsprite[showIamgeIs];

                }
            }
            else
            {
                showIamgeIs = 0;
                for (int i = 0; i < loadsprite.Count; i++)
                {
                    go.GetComponent().sprite = loadsprite[0];
                }
            }
            Debug.Log(showIamgeIs);
        }
    }
}
 

你可能感兴趣的:(unity)