In the second tutorial, Creating a Chart, we briefly mentioned the Text Annotations API to write Hello World on the chart.
This API also It lets you to add other UI elements to a chart, like:
- Lines
- Text
- Boxes
- Arrows
- Android Views, like, e.g., an ImageView
- custom Markers
Chart Annotations in SciChart
The SciChart annotations derive from the IAnnotation interface.
This annotation types include:
- AxisMarkerAnnotation
- BoxAnnotation
- HorizontalLineAnnotation
- LineAnnotation
- LineArrowAnnotation
- TextAnnotation
- VerticalLineAnnotation
- Android Views using CustomAnnotation
Adding Annotations to the Chart
In this tutorial, we are going to build on the previous tutorial. We will add a bulletin type marker (e.g., text, like a stock ticker or news item) to the chart.
To do this, we will modify the updateDataTask.
We create a TextAnnotation and add it to the Annotations collection of the SciChartSurface. We use SciChartBuilder to create and configure the annotation.
The modified code is shown below:
Example Title |
Copy Code |
---|---|
final int fifoCapacity = 500; final XyDataSeries lineData = sciChartBuilder.newXyDataSeries(Integer.class, Double.class) .withFifoCapacity(fifoCapacity) .build(); final XyDataSeries scatterData = sciChartBuilder.newXyDataSeries(Integer.class, Double.class) .withFifoCapacity(fifoCapacity) .build(); TimerTask updateDataTask = new TimerTask() { private int x = 0; @Override public void run() { UpdateSuspender.using(surface, new Runnable() { @Override public void run() { lineData.append(x, Math.sin(x * 0.1)); scatterData.append(x, Math.cos(x * 0.1)); // New code here // Add an annotation every 100 data points if(x%100 == 0) { TextAnnotation marker = sciChartBuilder.newTextAnnotation() .withIsEditable(false) .withText("N") .withBackgroundColor(ColorUtil.Green) .withX1(x) .withY1(0.0) .withVerticalAnchorPoint(VerticalAnchorPoint.Center) .withHorizontalAnchorPoint(HorizontalAnchorPoint.Center) .withFontStyle(20, ColorUtil.White) .withZIndex(1) .build(); surface.getAnnotations().add(marker); // Remove one annotation from the beginning // in the FIFO way if(x > fifoCapacity){ surface.getAnnotations().remove(0); } } // Zoom series to fit the viewport surface.zoomExtents(); ++x; } }); } }; Timer timer = new Timer(); long delay = 0; long interval = 10; timer.schedule(updateDataTask, delay, interval); |
This code from produces this following chart where we have added the letter N as a TextAnnotation as each points where x is a multiple of 100.
Further Reading
You can find out more about the Annotations API in the relevant section of the documentation: What Is an Annotation. Also, there is a couple of examples showcasing annotations in the SciChart Android Examples Suite.