当前位置:   article > 正文

unity 动态加载本地图片及排版功能_unity directory 加载图片

unity directory 加载图片

 

加载本地图片功能接口

  1. public void LoadLocalTextures(){
  2. string imgType="*.BMP|*.JPG|*.PNG"; //需要加载的图片类型后缀
  3. string[] imgTypes=imgType.Split('|');
  4. for (int i = 0; i < ImgType.Length; i++)
  5. {
  6. string[] s2 = Directory.GetFiles(PictureStr, ImgType[i]); //PictureStr 为图片所在路径
  7. for (int ji = 0; ji < s2.Length; ji++)
  8. {
  9. GameObject ga = Instantiate(Picture_Button, Picture_Grid.transform) as GameObject; //创建button实例,父节点为网格组件
  10. //文件流读取图片
  11. FileStream fileStream = new FileStream(s2[ji], FileMode.Open, FileAccess.Read);
  12. byte[] bytes = new byte[fileStream.Length];
  13. fileStream.Read(bytes, 0, (int)fileStream.Length);
  14. fileStream.Close();
  15. fileStream.Dispose();
  16. fileStream = null;
  17. //设置图片大小
  18. int width = 400;
  19. int height = 400;
  20. //创建texture2D
  21. Texture2D texture = new Texture2D(width, height);
  22. //加载图片流
  23. texture.LoadImage(bytes);
  24. //创建sprite并赋值
  25. Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
  26. ga.GetComponent<Image>().sprite = sprite;
  27. }
  28. }
  29. }

网格按钮自动排版:

UI层级

Picture_ScrollView 对象添加添加scrollRect组件

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class AutoSortGrid : MonoBehaviour
  6. {
  7. private RectTransform[] GradChildRectTrans;
  8. private float targetWidth, targetHeight, gridWidth, gridHeight, cellSizeX, cellSizeY, spacingX, spacingY;
  9. int gridChildCount = 0;
  10. public void UpdateAutoSort()
  11. {
  12. gridWidth = GetComponent<RectTransform>().rect.width;
  13. gridHeight = GetComponent<RectTransform>().rect.height;
  14. cellSizeX = GetComponent<GridLayoutGroup>().cellSize.x;
  15. cellSizeY = GetComponent<GridLayoutGroup>().cellSize.y;
  16. spacingX = GetComponent<GridLayoutGroup>().spacing.x;
  17. spacingY = GetComponent<GridLayoutGroup>().spacing.y;
  18. if (transform.childCount > 0)
  19. {
  20. gridChildCount = transform.childCount;
  21. int x = (int)(gridWidth / (spacingX + cellSizeX));
  22. int yCount = gridChildCount / x;
  23. float yHeight = (spacingY + cellSizeY) * yCount;
  24. if (yHeight > gridHeight)
  25. {
  26. transform.GetComponent<RectTransform>().sizeDelta = new Vector2(gridWidth, yHeight + 500f);
  27. }
  28. }
  29. }
  30. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/103575
推荐阅读
相关标签
  

闽ICP备14008679号