Closed HSyr closed 5 years ago
Make custom style like this:
class ColorStyle : TextStyle
{
public ColorStyle(Brush foreBrush, Brush backgroundBrush, FontStyle fontStyle) : base(foreBrush, backgroundBrush, fontStyle)
{
}
public override void Draw(Graphics gr, Point position, Range range)
{
//get color name
var parts = range.Text.Split('.');
var colorName = parts[parts.Length - 1];
//create color
var color = Color.FromName(colorName);
//assugn color ro backgrouns brush
(BackgroundBrush as SolidBrush).Color = color;
//draw
base.Draw(gr, position, range);
}
}
Then make highlighting:
private ColorStyle colorStyle = new ColorStyle(Brushes.Black, Brushes.White, FontStyle.Regular);
private void fctb_TextChanged(object sender, TextChangedEventArgs e)
{
e.ChangedRange.SetStyle(colorStyle, @"Color\.\w+");
}
Thank you very much. Works great! I end up with the following code changes:
class ColorStyle : TextStyle
{
public ColorStyle ( Brush foreBrush, Brush backgroundBrush, FontStyle fontStyle ) : base( foreBrush, backgroundBrush, fontStyle ) { }
public override void Draw ( Graphics gr, Point position, Range range )
{
Color color = Color.FromName( range.Text.Substring( range.Text.LastIndexOf( '.' ) + 1 ) );
// Test whether the Color exists
if ( color.A == 0 )
color = Color.White;
( BackgroundBrush as SolidBrush ).Color = color;
( ForeBrush as SolidBrush ).Color = BlackOrWhite( color );
base.Draw( gr, position, range );
}
public static Color BlackOrWhite ( Color color )
{
int light = 2126 * ( color.R * color.R ) + 7152 * ( color.G * color.G ) + 0722 * ( color.B * color.B );
return light > 5000 * 256 * 256 ? Color.Black : Color.White;
}
}
The rest is as you suggested.
In my project I formerly used
RichTextBox
with code highlighting written by myself. Apart from highlighting language elements I also formatted the .NETColor.*
items with their real color like this:I switched from
RichTextBox
to the much betterFastColoredTextBox
in my project. What is the best way to achieve the same Color formatting with your control?Thank you for the recommendation.