UnityCommon/base/richText/RichText.cs
2024-12-04 10:26:19 +08:00

69 lines
1.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class RichText : MonoBehaviour
{
[Header("文本预制体")] public GameObject textItem;
private string text = "";
public string Text
{
[DebuggerStepThrough] get => text;
[DebuggerStepThrough]
set
{
text = value;
Debug.Log("===------");
Debug.Log("<p>" + text + "</p>");
foreach (string item in SplitStringByTags("<p>" + text + "</p>", 23))
{
GameObject gameObject = Instantiate(textItem, GameObject.Find(name).transform);
gameObject.GetComponent<TextItem>().updateText(item);
}
}
}
public static string[] SplitStringByTags(string input, int maxLength)
{
// 使用正则表达式匹配 <p> 标签以及其中的内容
var regex = new System.Text.RegularExpressions.Regex(@"<p>(.*?)</p>");
var matches = regex.Matches(input);
// 用于存储结果
var resultList = new System.Collections.Generic.List<string>();
foreach (System.Text.RegularExpressions.Match match in matches)
{
string line = match.Groups[1].Value; // 获取<p>和</p>之间的内容
if (line.Length > maxLength)
{
// 如果行的长度大于maxLength则拆分成多个子字符串
for (int i = 0; i < line.Length; i += maxLength)
{
int length = Math.Min(maxLength, line.Length - i);
resultList.Add(line.Substring(i, length));
}
}
else
{
resultList.Add(line);
}
}
return resultList.ToArray();
}
// Update is called once per frame
void Update()
{
}
}