PavelTorgashov / FastColoredTextBox

Fast Colored TextBox for Syntax Highlighting. The text editor component for .NET.
Other
1.21k stars 464 forks source link

True Color coloring #157

Closed HSyr closed 5 years ago

HSyr commented 5 years ago

In my project I formerly used RichTextBoxwith code highlighting written by myself. Apart from highlighting language elements I also formatted the .NET Color.* items with their real color like this:

image

I switched from RichTextBox to the much better FastColoredTextBoxin my project. What is the best way to achieve the same Color formatting with your control?

Thank you for the recommendation.

PavelTorgashov commented 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+");
        }

Скриншот 2019-05-20 17 43 13

HSyr commented 5 years ago

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.