一、Unity 图片按照图片文字排版
1.准备好一张白底蓝字图片,尺寸不宜过大(字可以是其他颜色)

2.获取文字图片
public Texture2D wordTexture;
private List<Vector3> wordPosList = new List<Vector3>();
public string wordPath = “替换成自己的文字图片路径”;
star(){
wordTexture = GetTexture(wordPath);
if (wordPosList.Count == 0)
{
wordPosList.AddRange(GetWordPosByTexture(wordTexture));
}
}
private Texture2D GetTexture(string path)
{
List<Texture2D> textureList = new List<Texture2D>();
textureList = LoadImages(path);
if (textureList == null || textureList.Count == 0)
{
Debug.LogError("文字图片缺失");
return null;
}
return textureList[0];
}
public List<Texture2D> LoadImages(string imagePath)
{
List<Texture2D> texList = new List<Texture2D>();
List<string> filePaths = new List<string>();
string imgtype = ".bmp|.jpg|.png";
string[] ImageType = imgtype.Split('|');
if (Directory.Exists(imagePath))
{
DirectoryInfo direc = new DirectoryInfo(imagePath);
for (int i = 0; i < ImageType.Length; i++)
{
FileInfo[] files = direc.GetFiles("*", SearchOption.AllDirectories);
for (int j = 0; j < files.Length; ++j)
{
if (files[j].Name.EndsWith(ImageType[i]))
{
filePaths.Add(imagePath + files[j].Name);
}
}
}
}
for (int i = 0; i < filePaths.Count; i++)
{
Texture2D tx = new Texture2D(100, 100);
tx.LoadImage(getImageByte(filePaths[i]));
texList.Add(tx);
}
return texList;
}
public 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;
}
3.获取像素点
private int wordWidthStep = 20;
private int wordHeightStep = 20;
List<Vector3> GetWordPosByTexture(Texture2D texture)
{
List<Vector3> posList = new List<Vector3>();
int num = 0;
if (texture != null)
{
int width = texture.width ;
int height = texture.height ;
Color[] colors = texture.GetPixels();
for (int i = 0; i < height; i += wordHeightStep)
{
for (int j = 0; j < width; j += wordWidthStep)
{
int index = i * width + j;
if (nearBlack(colors[index]))
{
num++;
Vector3 itemPos = new Vector3();
itemPos.x = (j - (width / 2))* ScaleValue*1.5f;
itemPos.y = (i - (height / 2))* ScaleValue*1.5f;
itemPos.z = 0;
posList.Add(itemPos);
}
}
}
Debug.Log("数量数量wordPoint:" + num);
}
return posList;
}
bool nearBlack(Color color)
{
if (color.r < 0.8f || color.g < 0.8f || color.b < 0.8f)
return true;
else
return false;
4、图片按照文字像素点排列
IEnumerator SetPositionToItem(List<Vector3> pos)
{
for (int i = 0; i < pos.Count; i++)
{
Transform child = ListObj.transform.GetChild(i);
GameObject Obj = Instantiate(child.gameObject);
Obj.transform.SetParent(ListObj.transform, false);
RectTransform rectTransform = Obj.GetComponent<RectTransform>();
rectTransform.anchoredPosition = pos[i];
rectTransform.localScale = Vector3.one * 0.24f / ScaleValue;
clonedObjects.Add(Obj);
yield return null;
}
NoActionSaveFlag = false;
yield return null;
}
5、运行结果
