如何用图像替换文本(在flutter中是否可能)


var replaced = text.replaceAll(regExp, '*');

我们可以用实际图像代替星号吗。。

好的。所以你有一堆表情符号存储在本地。你必须用表情符号代替文字。

我没有一个完美的答案。但你如何才能走上我可以展示的道路。使用地图。假设要更改图像的文本,必须有一对。所以你可以为它定义一个地图。一个键将是一个文本,值将是表情符号的路径。将您的文件夹视为images,格式为png

Map<String, String> myData = {"like" : "images/like.png", "time": 
"images/time.png"};

等等。像这样,你可以创建一个完整的地图。如果它被限制为30-40条记录,你可以手动完成。

现在您可以对其执行操作。假设您具有字符串值=";我喜欢你的衬衫";所以我们需要扫描字符串,然后搜索地图中的每个单词,如果你找到了,就替换它。代码看起来像这个

void main() {
//your value that you are going to scan
String str = " I like your shirt";
//Defining the map
Map<String, String> data = {"like" : "images/like.png", "shirt" : 
"images/shirt.png", "happy" : "images/happy.png"};

//function that will do the changes and display 
void replaceTextWithEmojis(String value, Map<String, String> data){

//splitting the value into the array or list of items so we can iterate easily
List<String> inputvalues = str.split(" ");
//looping through the text
for (int i =0; i<inputvalues.length; i++){

//checking where that text is present in the emojis map or not.
if(data.containsKey(inputvalues[i])){

//this will replace the text with the path for that key
inputvalues[i] = data[inputvalues[i]];
}
} //end of the for loop
print(inputvalues);
}

replaceTextWithEmojis(str, data);
}

这将替换为所需的值。但是你想在文本之间显示一个图像。这真是太难了。我认为你做不到手忙脚乱。或者,您需要识别可替换文本的位置,然后中断字符串并将其存储在其他变量中。在断点处附加图像。所以在我们用地图替换的地方,你可以添加一个widget(child ImageProvider(inputvalue[i]));

我建议你使用unicode作为表情符号。您可以将该包用于unicode emjois:https://pub.dev/packages/emojis

他们也会给你更好的表现。

/// Replace an emoticon or any string token with an image having a tooltip and Help cursor.
static List<Widget> replaceEmoji(final String text, final String fromToken, final String toImgTooltip, final String toImg) {
Widget _getImage(final String path, final String tooltip) => MouseRegion(
cursor: SystemMouseCursors.help,
child: Tooltip(message: tooltip, child: Image.asset(path)),
);
if (!text.contains(fromToken)) {
return [Text(text)];
}
final result = <Widget>[];
var buffer = text;
var n = -1;
while (true) {
n = buffer.indexOf(fromToken);
if (n != 0) {
result.add(Text(buffer.substring(0, n)));
}
result.add(_getImage(toImg, toImgTooltip));
buffer = buffer.substring(n + fromToken.length);
if (buffer.isEmpty) {
break;
}
}
return result;
}

您使用它如下:

...
Wrap(
children: replaceEmoji('my :) face - :):)', ':)', 'smile', 'assets/images/emoji/smile.png')
)
...

最新更新