SciChart® the market leader in Fast WPF Charts, WPF 3D Charts, iOS Chart, Android Chart and JavaScript Chart Components
SciChart Android ships with ~90Â Android Chart Examples which you can browse, play with, view the source-code and even export each SciChart Android Chart Example to a stand-alone Android Studio project. All of this is possible with the new and improved SciChart Android Examples Suite, which ships as part of our Android Charts SDK.
This example demonstrates how to create a custom animation and have complete control over data appearing on the screen. It shows how to animate the last appended point to a Line Series in real-time.
The full source code for the Android Animating Line Chart example example is included below (Scroll down!).
Did you know you can also view the source code from one of the following sources as well?
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2021. All rights reserved.
//
// Web: http://www.scichart.com
// Support: support@scichart.com
// Sales: sales@scichart.com
//
// AnimatingLineChartFragment.kt is part of SCICHART®, High Performance Scientific Charts
// For full terms and conditions of the license, see http://www.scichart.com/scichart-eula/
//
// This source code is protected by international copyright law. Unauthorized
// reproduction, reverse-engineering, or distribution of all or any portion of
// this source code is strictly prohibited.
//
// This source code contains confidential and proprietary trade secrets of
// SciChart Ltd., and should at no time be copied, transferred, sold,
// distributed or made available without express written permission.
//******************************************************************************
package com.scichart.examples.fragments.examples2d.createCustomAnimations.kt
import android.animation.FloatEvaluator
import android.os.Bundle
import android.view.animation.DecelerateInterpolator
import com.scichart.charting.visuals.SciChartSurface
import com.scichart.charting.visuals.animations.AnimationsHelper
import com.scichart.charting.visuals.animations.BaseRenderPassDataTransformation
import com.scichart.charting.visuals.animations.TransformationHelpers
import com.scichart.charting.visuals.axes.AutoRange
import com.scichart.charting.visuals.renderableSeries.FastLineRenderableSeries
import com.scichart.charting.visuals.renderableSeries.data.LineRenderPassData
import com.scichart.core.framework.UpdateSuspender
import com.scichart.core.model.FloatValues
import com.scichart.data.model.DoubleRange
import com.scichart.data.model.ISciList
import com.scichart.examples.R
import com.scichart.examples.fragments.base.ExampleSingleChartBaseFragment
import com.scichart.examples.utils.scichartExtensions.*
import com.scichart.examples.utils.widgetgeneration.ImageViewWidget
import com.scichart.examples.utils.widgetgeneration.Widget
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class AnimatingLineChartFragment : ExampleSingleChartBaseFragment() {
private val scheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
private lateinit var schedule: ScheduledFuture<*>
@Volatile
private var isRunning = true
private val dataSeries = XyDataSeries<Double, Double>().apply { fifoCapacity = FIFO_CAPACITY }
private val rSeries = FastLineRenderableSeries().apply {
dataSeries = this@AnimatingLineChartFragment.dataSeries
strokeStyle = SolidPenStyle(0xFF4083B7, 3f)
}
private val xVisibleRange = DoubleRange(-1.0, VISIBLE_RANGE_MAX)
private var currentXValue = 0.0
private var yValue = 0.0
private val animator = AnimationsHelper.createAnimator(
rSeries,
AppendedPointTransformation(),
ANIMATION_DURATION,
0,
DecelerateInterpolator(),
FloatEvaluator(),
0f, 1f
)
override fun showDefaultModifiersInToolbar(): Boolean { return false }
override fun getToolbarItems(): List<Widget> = ArrayList<Widget>().apply {
add(ImageViewWidget.Builder().setId(R.drawable.example_toolbar_play).setListener { isRunning = true }.build())
add(ImageViewWidget.Builder().setId(R.drawable.example_toolbar_pause).setListener { isRunning = false }.build())
add(ImageViewWidget.Builder().setId(R.drawable.example_toolbar_stop).setListener {
isRunning = false
resetChart()
}.build())
}
override fun initExample(surface: SciChartSurface) {
surface.suspendUpdates {
xAxes {
numericAxis {
autoRange = AutoRange.Never
visibleRange = xVisibleRange
}
}
yAxes {
numericAxis {
visibleRange = DoubleRange(0.0, MAX_Y_VALUE)
growBy = DoubleRange(0.1, 0.1)
}
}
renderableSeries { rSeries(rSeries) }
}
addPointAnimated()
schedule = scheduledExecutorService.scheduleWithFixedDelay(insertRunnable, 0, TIME_INTERVAL, TimeUnit.MILLISECONDS)
}
private val insertRunnable = Runnable {
if (!isRunning) return@Runnable
addPointAnimated()
}
private fun addPointAnimated() {
activity?.runOnUiThread {
animator.cancel()
binding.surface.suspendUpdates {
yValue = random.nextDouble() * MAX_Y_VALUE
dataSeries.append(currentXValue, yValue)
}
animator.start()
currentXValue += X_RANGE_STEP
animateVisibleRangeIfNeeded()
}
}
private fun animateVisibleRangeIfNeeded() {
if (currentXValue > VISIBLE_RANGE_MAX) {
val xAxis = binding.surface.xAxes[0]
val newRange = DoubleRange(
xAxis.visibleRange.minAsDouble + X_RANGE_STEP,
xAxis.visibleRange.maxAsDouble + X_RANGE_STEP
)
xAxis.animateVisibleRangeTo(newRange, ANIMATION_DURATION)
}
}
private fun resetChart() {
UpdateSuspender.using(binding.surface) { dataSeries.clear() }
currentXValue = 0.0
binding.surface.xAxes.firstOrNull()?.animateVisibleRangeTo(DoubleRange(-1.0, VISIBLE_RANGE_MAX), ANIMATION_DURATION)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
isRunning = false
outState.putDouble("currentXValue", currentXValue)
outState.putDouble("yValue", yValue)
outState.putDouble("xVisibleRangeMin", xVisibleRange.minAsDouble)
outState.putDouble("xVisibleRangeMax", xVisibleRange.maxAsDouble)
outState.putParcelable("xValues1", dataSeries.xValues)
outState.putParcelable("yValues1", dataSeries.yValues)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
savedInstanceState?.run {
currentXValue = getDouble("currentXValue")
yValue = getDouble("yValue")
val xVisibleRangeMin = getDouble("xVisibleRangeMin")
val xVisibleRangeMax = getDouble("xVisibleRangeMax")
xVisibleRange.setMinMaxDouble(xVisibleRangeMin, xVisibleRangeMax)
val xValues1: ISciList<Double> = getParcelable("xValues1")!!
val yValues1: ISciList<Double> = getParcelable("yValues1")!!
dataSeries.append(xValues1, yValues1)
}
}
override fun onDestroyView() {
super.onDestroyView()
schedule.cancel(true)
}
companion object {
private const val FIFO_CAPACITY = 50
private const val TIME_INTERVAL: Long = 1000
private const val ANIMATION_DURATION: Long = 500
private const val X_RANGE_STEP = 1.0
private const val VISIBLE_RANGE_MAX = 10.0
private const val MAX_Y_VALUE = 100.0
private val random = Random()
}
private class AppendedPointTransformation: BaseRenderPassDataTransformation<LineRenderPassData>(LineRenderPassData::class.java) {
private val originalXCoordinates = FloatValues()
private val originalYCoordinates = FloatValues()
override fun saveOriginalData() {
if (!renderPassData.isValid) return
TransformationHelpers.copyData(renderPassData.xCoords, originalXCoordinates)
TransformationHelpers.copyData(renderPassData.yCoords, originalYCoordinates)
}
override fun applyTransformation() {
if (!renderPassData.isValid) return
val count = renderPassData.pointsCount()
val firstXStart = renderPassData.xCoordinateCalculator.getCoordinate(0.0)
val xStart = if (count <= 1) firstXStart else originalXCoordinates.get(count - 2)
val xFinish = originalXCoordinates.get(count - 1)
val additionalX = xStart + (xFinish - xStart) * currentTransformationValue
renderPassData.xCoords.set(count - 1, additionalX)
val firstYStart = renderPassData.yCoordinateCalculator.getCoordinate(0.0)
val yStart = if (count <= 1) firstYStart else originalYCoordinates.get(count - 2)
val yFinish = originalYCoordinates.get(count - 1)
val additionalY = yStart + (yFinish - yStart) * currentTransformationValue
renderPassData.yCoords.set(count - 1, additionalY)
}
override fun discardTransformation() {
TransformationHelpers.copyData(originalXCoordinates, renderPassData.xCoords)
TransformationHelpers.copyData(originalYCoordinates, renderPassData.yCoords)
}
override fun onInternalRenderPassDataChanged() {
applyTransformation()
}
}
}
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2021. All rights reserved.
//
// Web: http://www.scichart.com
// Support: support@scichart.com
// Sales: sales@scichart.com
//
// AnimatingLineChartFragment.java is part of SCICHART®, High Performance Scientific Charts
// For full terms and conditions of the license, see http://www.scichart.com/scichart-eula/
//
// This source code is protected by international copyright law. Unauthorized
// reproduction, reverse-engineering, or distribution of all or any portion of
// this source code is strictly prohibited.
//
// This source code contains confidential and proprietary trade secrets of
// SciChart Ltd., and should at no time be copied, transferred, sold,
// distributed or made available without express written permission.
//******************************************************************************
package com.scichart.examples.fragments.examples2d.createCustomAnimations;
import android.animation.Animator;
import android.animation.FloatEvaluator;
import android.os.Bundle;
import android.view.animation.DecelerateInterpolator;
import androidx.annotation.NonNull;
import com.scichart.charting.model.dataSeries.IXyDataSeries;
import com.scichart.charting.visuals.SciChartSurface;
import com.scichart.charting.visuals.animations.AnimationsHelper;
import com.scichart.charting.visuals.animations.BaseRenderPassDataTransformation;
import com.scichart.charting.visuals.animations.TransformationHelpers;
import com.scichart.charting.visuals.axes.AutoRange;
import com.scichart.charting.visuals.axes.IAxis;
import com.scichart.charting.visuals.axes.NumericAxis;
import com.scichart.charting.visuals.renderableSeries.FastLineRenderableSeries;
import com.scichart.charting.visuals.renderableSeries.data.LineRenderPassData;
import com.scichart.core.framework.UpdateSuspender;
import com.scichart.core.model.FloatValues;
import com.scichart.data.model.DoubleRange;
import com.scichart.data.model.IRange;
import com.scichart.data.model.ISciList;
import com.scichart.examples.R;
import com.scichart.examples.fragments.base.ExampleSingleChartBaseFragment;
import com.scichart.examples.utils.widgetgeneration.ImageViewWidget;
import com.scichart.examples.utils.widgetgeneration.Widget;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class AnimatingLineChartFragment extends ExampleSingleChartBaseFragment {
private final static int FIFO_CAPACITY = 50;
private final static long TIME_INTERVAL = 1000;
private final static long ANIMATION_DURATION = 500;
private final static double X_RANGE_STEP = 1.0;
private final static double VISIBLE_RANGE_MAX = 10.0;
private final static double MAX_Y_VALUE = 100.0;
private final Random random = new Random();
private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> schedule;
private volatile boolean isRunning = true;
private final IXyDataSeries<Double, Double> dataSeries = sciChartBuilder.newXyDataSeries(Double.class, Double.class)
.withFifoCapacity(FIFO_CAPACITY).build();
private final FastLineRenderableSeries rSeries = sciChartBuilder.newLineSeries()
.withDataSeries(dataSeries)
.withStrokeStyle(sciChartBuilder.newPen().withColor(0xFF4083B7).withThickness(3f).build())
.build();
private final DoubleRange xVisibleRange = new DoubleRange(-1.0, VISIBLE_RANGE_MAX);
private double currentXValue = 0;
private double yValue = 0;
private Animator animator = AnimationsHelper.createAnimator(
rSeries,
new AppendedPointTransformation(),
ANIMATION_DURATION,
0,
new DecelerateInterpolator(),
new FloatEvaluator(),
0f, 1f
);
@Override
public boolean showDefaultModifiersInToolbar() {
return false;
}
@NonNull
@Override
public List<Widget> getToolbarItems() {
return new ArrayList<Widget>() {{
add(new ImageViewWidget.Builder().setId(R.drawable.example_toolbar_play).setListener(v -> isRunning = true).build());
add(new ImageViewWidget.Builder().setId(R.drawable.example_toolbar_pause).setListener(v -> isRunning = false).build());
add(new ImageViewWidget.Builder().setId(R.drawable.example_toolbar_stop).setListener(v -> {
isRunning = false;
resetChart();
}).build());
}};
}
@Override
protected void initExample(@NonNull SciChartSurface surface) {
UpdateSuspender.using(surface, () -> {
final NumericAxis xAxis = sciChartBuilder.newNumericAxis()
.withAutoRangeMode(AutoRange.Never)
.withVisibleRange(xVisibleRange)
.build();
final NumericAxis yAxis = sciChartBuilder.newNumericAxis()
.withVisibleRange(new DoubleRange(0.0, MAX_Y_VALUE))
.withGrowBy(new DoubleRange(0.1d, 0.1d))
.build();
Collections.addAll(surface.getXAxes(), xAxis);
Collections.addAll(surface.getYAxes(), yAxis);
Collections.addAll(surface.getRenderableSeries(), rSeries);
});
addPointAnimated();
schedule = scheduledExecutorService.scheduleWithFixedDelay(() -> {
if (!isRunning) {
return;
}
UpdateSuspender.using(surface, insertRunnable);
}, 0, TIME_INTERVAL, TimeUnit.MILLISECONDS);
}
private final Runnable insertRunnable = this::addPointAnimated;
private void addPointAnimated() {
requireActivity().runOnUiThread(() -> {
animator.cancel();
UpdateSuspender.using(binding.surface, () -> {
yValue = random.nextDouble() * MAX_Y_VALUE;
dataSeries.append(currentXValue, yValue);
});
animator.start();
currentXValue += X_RANGE_STEP;
animateVisibleRangeIfNeeded();
});
}
private void animateVisibleRangeIfNeeded() {
if (currentXValue > VISIBLE_RANGE_MAX) {
IAxis xAxis = binding.surface.getXAxes().get(0);
IRange newRange = new DoubleRange(
xAxis.getVisibleRange().getMinAsDouble() + X_RANGE_STEP,
xAxis.getVisibleRange().getMaxAsDouble() + X_RANGE_STEP
);
xAxis.animateVisibleRangeTo(newRange, ANIMATION_DURATION);
}
}
private void resetChart() {
UpdateSuspender.using(binding.surface, dataSeries::clear);
currentXValue = 0.0;
binding.surface.getXAxes().get(0).animateVisibleRangeTo(new DoubleRange(-1.0, VISIBLE_RANGE_MAX), ANIMATION_DURATION);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
isRunning = false;
outState.putDouble("currentXValue", currentXValue);
outState.putDouble("yValue", yValue);
outState.putDouble("xVisibleRangeMin", xVisibleRange.getMinAsDouble());
outState.putDouble("xVisibleRangeMax", xVisibleRange.getMaxAsDouble());
outState.putParcelable("xValues1", dataSeries.getXValues());
outState.putParcelable("yValues1", dataSeries.getYValues());
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
currentXValue = savedInstanceState.getDouble("currentXValue");
yValue = savedInstanceState.getDouble("yValue");
final double xVisibleRangeMin = savedInstanceState.getDouble("xVisibleRangeMin");
final double xVisibleRangeMax = savedInstanceState.getDouble("xVisibleRangeMax");
xVisibleRange.setMinMaxDouble(xVisibleRangeMin, xVisibleRangeMax);
final ISciList<Double> xValues1 = savedInstanceState.getParcelable("xValues1");
final ISciList<Double> yValues1 = savedInstanceState.getParcelable("yValues1");
dataSeries.append(xValues1, yValues1);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (schedule != null) {
schedule.cancel(true);
}
}
private static class AppendedPointTransformation extends BaseRenderPassDataTransformation<LineRenderPassData> {
private final FloatValues originalXCoordinates = new FloatValues();
private final FloatValues originalYCoordinates = new FloatValues();
protected AppendedPointTransformation() {
super(LineRenderPassData.class);
}
@Override
protected void saveOriginalData() {
if (!renderPassData.isValid()) return;
TransformationHelpers.copyData(renderPassData.xCoords, originalXCoordinates);
TransformationHelpers.copyData(renderPassData.yCoords, originalYCoordinates);
}
@Override
protected void applyTransformation() {
if (!renderPassData.isValid()) return;
int count = renderPassData.pointsCount();
float currentTransformationValue = getCurrentTransformationValue();
float xStart;
if (count <= 1) {
xStart = renderPassData.getXCoordinateCalculator().getCoordinate(0.0);
} else {
xStart = originalXCoordinates.get(count - 2);
}
float xFinish = originalXCoordinates.get(count - 1);
float additionalX = xStart + (xFinish - xStart) * currentTransformationValue;
renderPassData.xCoords.set(count - 1, additionalX);
float yStart;
if (count <= 1) {
yStart = renderPassData.getYCoordinateCalculator().getCoordinate(0.0);
} else {
yStart = originalYCoordinates.get(count - 2);
}
float yFinish = originalYCoordinates.get(count - 1);
float additionalY = yStart + (yFinish - yStart) * currentTransformationValue;
renderPassData.yCoords.set(count - 1, additionalY);
}
@Override
protected void discardTransformation() {
TransformationHelpers.copyData(originalXCoordinates, renderPassData.xCoords);
TransformationHelpers.copyData(originalYCoordinates, renderPassData.yCoords);
}
@Override
protected void onInternalRenderPassDataChanged() {
applyTransformation();
}
}
}