Предварительный просмотр:
Обновления:
Добавлена поддержка выделения цвета.
Код:
Протестировано на .NET Compact Framework 3.5, Windows Mobile 6 SDK, вероятно, должно работать и на .NET Framework.
/// <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