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