Search code examples
oxyplot

In OxyPlot, how to add a TextAnnotation that is relative to the PlotArea a not bound to the axes?


I would like to add a TextAnnotation that is positioned in a specific location on the plot area in a way that it is independent of the axis pan or zoom - similar to a watermark.

I noticed the TextAnnotation position can only be determined by a DataPoint, while the ImageAnnotation has the X and Y properties for positioning.


Solution

  • It is easy to create a custom one:

    public class CustomTextAnnotation : Annotation
    { 
        public CustomTextAnnotation()
        { } 
    
        public string Text { get; set; }
        public double X { get; set; } 
        public double Y { get; set; }
    
        public override void Render(IRenderContext rc)
        {
            base.Render(rc);
            double pX = PlotModel.PlotArea.Left + X;
            double pY = PlotModel.PlotArea.Top + Y;
            rc.DrawMultilineText(new ScreenPoint(pX, pY), Text, TextColor, Font, FontSize, FontWeight);
        }  
    }
    

    Please note that you should set the Font, FontSize, etc.:

     plotModel.Annotations.Add(new CustomTextAnnotation() {
              Text = "A B C",
              X = 110,
              Y = 10,
              Font = "Times New Roman",
              FontSize = 12,
              TextColor = OxyColors.Black });
    

    Also, please note that you can add other properties such as border colors and other stuff too, however, things might get complicated (I didn't try).

    Hope it helps: