OcrTextHighlighterConverter.cs 2.1 KB
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;

namespace SmartScan.SetControl.WPF.Convent
{
    public class OcrTextHighlighterConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            string text = value.ToString();

            // 创建一个TextBlock
            TextBlock textBlock = new TextBlock
            {
                TextWrapping = TextWrapping.Wrap,
                HorizontalAlignment = HorizontalAlignment.Stretch
            };

            // 检查文本是否包含"<OCR>"
            int ocrIndex = text.IndexOf("<OCR>", StringComparison.OrdinalIgnoreCase);

            if (ocrIndex < 0)
            {
                // 如果不包含OCR标记,直接添加整个文本
                textBlock.Inlines.Add(new Run(text) { Foreground = Brushes.White });
            }
            else
            {
                // 添加OCR标记前的文本
                if (ocrIndex > 0)
                {
                    textBlock.Inlines.Add(new Run(text.Substring(0, ocrIndex)) { Foreground = Brushes.White });
                }

                // 添加红色的OCR标记
                textBlock.Inlines.Add(new Run("<OCR>") { Foreground = Brushes.Red });

                // 添加OCR标记后的文本
                if (ocrIndex + 5 < text.Length)
                {
                    textBlock.Inlines.Add(new Run(text.Substring(ocrIndex + 5)) { Foreground = Brushes.White });
                }
            }

            return textBlock;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}