突出显示文本标签中的多个字符

时间:2010-11-04 09:22:58

标签: .net colors label highlighting

我正在寻找一种使用.NET Compact Framework突出显示文本标签中多个字符的方法。例如。在包含文字Hello World的标签中,我希望在此示例中突出显示Hr

  

H ello Wo r ld

我最初的解决方案是滥用&为目标字符加下划线,但遗憾的是它只会强调一个字符。我不在乎角色是用不同的颜色,粗体还是下划线,唯一重要的是它们脱颖而出。

1 个答案:

答案 0 :(得分:0)

预览

Preview

<强>更新

添加了颜色突出显示支持。

<强>代码:

在.NET Compact Framework 3.5上测试,Windows Mobile 6 SDK也可能适用于.NET框架。

/// <summary>
/// A label which offers you the possibility to highlight characters 
/// at defined positions.
/// See <see cref="HighlightPositions"/>, <see cref="HighlightStyle"/> and
/// <see cref="HighlightColor"/>
/// The text in the Text property will be displayed.
/// </summary>
public partial class HighlightLabel : Control
{
    /// <summary>
    /// Initializes a new instance of the class.
    /// </summary>
    public HighlightLabel()
    {
        InitializeComponent();
    }
    /// <summary>
    /// An array of all positions in the text to be highlighted.
    /// </summary>
    public int[] HighlightPositions { get; set; }

    /// <summary>
    /// Gets or sets the highlight style.
    /// </summary>
    public FontStyle HighlightStyle { get; set; }

    /// <summary>
    /// Gets or sets the highlight color.
    /// </summary>
    public Color HighlightColor { get; set; }

    // Paints the string and applies the highlighting style.
    protected override void OnPaint(PaintEventArgs e)
    {
        if (HighlightPositions == null)
            HighlightPositions = new int[] { };

        var usedOffsets = new List<float>();

        for (var i = 0; i < Text.Length; i++)
        {
            var characterToPaint =
                Text[i].ToString(CultureInfo.CurrentCulture);

            var selectedFont = Font;
            var selectedColor = ForeColor;

            if (HighlightPositions.Contains(i))
            {
                selectedColor = HighlightColor;
                selectedFont = new Font(Font.Name, Font.Size, 
                    HighlightStyle);
            }

            var currentOffset = usedOffsets.Sum();

            e.Graphics.DrawString(characterToPaint, selectedFont,
                new SolidBrush(selectedColor),
                new RectangleF(e.ClipRectangle.X + currentOffset,
                    e.ClipRectangle.Y, e.ClipRectangle.Width,
                    e.ClipRectangle.Height));

            var offset = e.Graphics.MeasureString(characterToPaint,
                selectedFont).Width;

            usedOffsets.Add(offset);
        }
    }
}

<强>用法:

highlightLabel.HighlightPositions = new[] { 1, 8 };
highlightLabel.HighlightStyle = FontStyle.Bold;
highlightLabel.HighlightColor = Color.Red