0
我正在寻找一种方法来使用.NET Compact Framework突出显示文本标签中的多个字符。例如。其中包含文本Hello World
一个标签,我想H
和r
突出就像这个例子:突出显示文本标签中的多个字符
^h ELLO禾[R LD
我最初的解决方案是滥用&
以强调目标角色,但不幸的是它只会强调一个角色。我不在乎这些角色的颜色是不同的,大胆的还是强调的,唯一重要的是他们脱颖而出。
我正在寻找一种方法来使用.NET Compact Framework突出显示文本标签中的多个字符。例如。其中包含文本Hello World
一个标签,我想H
和r
突出就像这个例子:突出显示文本标签中的多个字符
^h ELLO禾[R LD
我最初的解决方案是滥用&
以强调目标角色,但不幸的是它只会强调一个角色。我不在乎这些角色的颜色是不同的,大胆的还是强调的,唯一重要的是他们脱颖而出。
前瞻:
更新:
添加颜色高亮的支持。
代码:
测试在.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