Delphi Gestures with TeeChart

Since Embarcadero introduced touch screen support, the way gestures are being handled has evolved. Now that we are in the RAD Studio XE8 days, it has become pretty straightforward as documented in their “Gesturing Overview” article.

DelphiGestures

That article lays out the foundation on how to work with touch gestures and controls. Applying that to TeeChart, means we’ll need TChart and TGestureManager components. TGestureManager, which manages all the gestures that can be used by the control, will have to be associated to TChart’s Touch property. There you can choose which gestures will be associated with the control. There are three kinds of gestures: standard, custom and interactive. The example discussed is based on Delphi’s interactive gestures example.

Here you can download the full project used for the article. Now I’ll explain how to create it. Before starting to write code, please do the following at design-time: add a TChart component, add a TGestureManger component, passing the gesture manager to TChart‘s Touch property and enable Zoom, Pan and DoubleTap interactive gestures on it.

Once this is done, it’s time to start typing code. First of all we’ll deactivate some TeeChart standard interactions so they don’t interfere with the functionality gestures will implement. So we will disable default zoom and panning in form’s OnCreate event:

procedure TForm1.FormCreate(Sender: TObject);
var
  Series1: TSurfaceSeries;
begin
  Series1 := TSurfaceSeries.Create(Self);
  Series1.FillSampleValues(10);
  Series1.UseColorRange := False;
  Series1.UsePalette := True;
  Series1.PaletteStyle := psStrong;

  Chart1.AddSeries(Series1);
  Chart1.Zoom.Allow := False;
  Chart1.Panning.Active := False;
  Chart1.Chart3DPercent := 50;

  with TFlatTheme.Create(Chart1) do
  try
    Apply;
  finally
    Free;
  end;
end;

After that, it’s the turn of TChart‘s OnGesture event implementation:

procedure TForm1.Chart1Gesture(Sender: TObject;
  const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
  if EventInfo.GestureID = igiZoom then
    handleZoom(EventInfo)
  else if EventInfo.GestureID = igiPan then
    handlePan(EventInfo)
  else if EventInfo.GestureID = igiDoubleTap then
    handleDoubleTap(EventInfo);

  Handled := True;
end;

We are checking for TInteractiveGestures gestures performed on the chart, using event’s TGestureEventInfo, and implement a specific gesture handler method for each one. Finally, we set the Handled parameter to True so that the event is not propagated further.

Let’s speak about gesture handler methods now, starting with zoom:

procedure TForm1.handleZoom(EventInfo: TGestureEventInfo);
var
  LObj: IControl;
  chart: TChart;
  zoom: Double;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
  begin
    if not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then
    begin
      chart := TChart(LObj.GetObject);
      zoom := (EventInfo.Distance / FLastDIstance) * chart.Aspect.ZoomFloat;
      chart.Aspect.ZoomFloat := Max(10, zoom);
    end;
  end;
  FLastDIstance := EventInfo.Distance;
end;

Here we are implementing something different and simpler than the standard zoom in TeeChart. It’s based on the difference between the current distance and pinch that the gesture provides and the distance saved from previous calls, not allowing a zoom factor smaller than 10% of the original size.

Let’s continue with the pan gesture which, in this example, will be used for rotating the chart instead of panning it:

procedure TForm1.handlePan(eventInfo: TGestureEventInfo);
var
  LObj: IControl;
  chart: TChart;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
  begin
    if not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then
    begin
      chart := TChart(LObj.GetObject);

      chart.Aspect.Orthogonal := False;
      chart.Aspect.RotationFloat := chart.Aspect.RotationFloat + (EventInfo.Location.X - FLastPosition.X);
      chart.Aspect.ElevationFloat := chart.Aspect.ElevationFloat - (EventInfo.Location.Y - FLastPosition.Y);
    end;

    FLastPosition := EventInfo.Location;
  end;
end;

Similar to the pinch zoom gesture, here displacement (calculated from the screen position) is being used to rotate and elevate the chart.

Finally, the double tap gesture:

procedure TForm1.handleDoubleTap(eventInfo: TGestureEventInfo);
var
  LObj: IControl;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
    ResetChart(TChart(LObj.GetObject));
end;

procedure TForm1.ResetChart(chart: TChart);
begin
  chart.Aspect.Orthogonal := True;
  chart.Aspect.ZoomFloat:=100;
  chart.Aspect.ElevationFloat:=345;
  chart.Aspect.RotationFloat:=345;
end;

It’s only used for resetting chart properties to their original values.

I hope this example is useful to illustrate the possibilities TeeChart has with multi-touch gesture on touch devices. It only covers a few cases but this opens up the possibility to a new world of charting interactions.

Here’s the complete code listing for the example discussed in this article:

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls, FMXTee.Engine, FMXTee.Procs,
  FMXTee.Chart, FMXTee.Series, FMXTee.Commander, FMX.Gestures,
  FMXTee.Series.Surface, FMXTee.Themes;

type
  TForm1 = class(TForm)
    Chart1: TChart;
    GestureManager1: TGestureManager;
    procedure FormCreate(Sender: TObject);
    procedure Chart1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo;
      var Handled: Boolean);
  private
    { Private declarations }
    FLastPosition: TPointF;
    FLastDistance: Integer;
    procedure handleZoom(eventInfo: TGestureEventInfo);
    procedure handlePan(eventInfo: TGestureEventInfo);
    procedure handleDoubleTap(eventInfo: TGestureEventInfo);
    procedure ResetChart(chart: TChart);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

uses System.Math;

procedure TForm1.Chart1Gesture(Sender: TObject;
  const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
  if EventInfo.GestureID = igiZoom then
    handleZoom(EventInfo)
  else if EventInfo.GestureID = igiPan then
    handlePan(EventInfo)
  else if EventInfo.GestureID = igiDoubleTap then
    handleDoubleTap(EventInfo);

  Handled := True;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  Series1: TSurfaceSeries;
begin
  Series1 := TSurfaceSeries.Create(Self);
  Series1.FillSampleValues(10);
  Series1.UseColorRange := False;
  Series1.UsePalette := True;
  Series1.PaletteStyle := psStrong;

  Chart1.AddSeries(Series1);
  Chart1.Zoom.Allow := False;
  Chart1.Panning.Active := False;
  Chart1.Chart3DPercent := 50;

  with TFlatTheme.Create(Chart1) do
  try
    Apply;
  finally
    Free;
  end;
end;

procedure TForm1.handleDoubleTap(eventInfo: TGestureEventInfo);
var
  LObj: IControl;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
    ResetChart(TChart(LObj.GetObject));
end;

procedure TForm1.handlePan(eventInfo: TGestureEventInfo);
var
  LObj: IControl;
  chart: TChart;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
  begin
    if not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then
    begin
      chart := TChart(LObj.GetObject);

      chart.Aspect.Orthogonal := False;
      chart.Aspect.RotationFloat := chart.Aspect.RotationFloat + (EventInfo.Location.X - FLastPosition.X);
      chart.Aspect.ElevationFloat := chart.Aspect.ElevationFloat - (EventInfo.Location.Y - FLastPosition.Y);
    end;

    FLastPosition := EventInfo.Location;
  end;
end;

procedure TForm1.handleZoom(EventInfo: TGestureEventInfo);
var
  LObj: IControl;
  chart: TChart;
  zoom: Double;
begin
  LObj := Self.ObjectAtPoint(ClientToScreen(EventInfo.Location));
  if LObj is TChart then
  begin
    if not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then
    begin
      chart := TChart(LObj.GetObject);
      zoom := (EventInfo.Distance / FLastDIstance) * chart.Aspect.ZoomFloat;
      chart.Aspect.ZoomFloat := Max(10, zoom);
    end;
  end;
  FLastDIstance := EventInfo.Distance;
end;

procedure TForm1.ResetChart(chart: TChart);
begin
  chart.Aspect.Orthogonal := True;
  chart.Aspect.ZoomFloat:=100;
  chart.Aspect.ElevationFloat:=345;
  chart.Aspect.RotationFloat:=345;
end;

end.

 

Theme persistence

2015 brings some aesthetic improvements for TeeChart VCL/FMX and .NET versions with the intention to make it easier for our users to create visually appealing charts. In this article I’m going to speak about difference aspects about new theme usage and possibilities in TeeChart VCL/FMX to accomplish that objective. The concept and the result is almost the same in TeeChart .NET. The only differences are mostly internal and hence transparent to the user.

We’ve started by creating two new themes: Lookout and Andros, with their associated color palettes: Lookout and Seawash respectively. This is how those themes look when displaying the full color palette or single color series:

LookoutExample2
Lookout theme example with one single color series
LookoutExample
Lookout theme example showing all the colors in the so called Lookout palette
SeaWashExample
Andros theme example showing all the colors in the associated Seawash palette
AndrosExample
Andros theme example showing a series with one single color from the Seawash palette.

However, this is only the tip of the iceberg because new themes also come with more theme related internal functionality. That is, when a custom theme is applied to a chart, new objects (series, axes and tools) added to it will also inherit the aspect of those themed objects which already exist in the chart. This didn’t occur before. So, for example, if you add a new series to a chart with one of those themes, series in in the chart will perpetuate their settings to additional series added afterwards. An example can be seen in the chart below, an additional series to a chart with the Andros theme will set the series marks to be exactly in the same format without having to perform any custom setting by the user.

Andros2Series
All series in this chart share series marks custom settings without the need of any specific code.

In the VCL/FMX version this applies to series, tools and custom axes, for now.

Going even further, users can add their own themes by exporting the charts they created to the TeeChart native template  format (.tee files). There’s just one thing they should bear in mind is that for series to be “themed” they should be of a special type in the custom theme file, TThemedSeries. For example:

  //Add themed series
  Chart1.AddSeries(TThemedSeries.Create(Self)).FillSampleValues;
  
  for i:=0 to Chart.SeriesCount-1 do
  begin
    Chart[i].Marks.Arrow.Visible:=False;
    Chart[i].Marks.Transparent:=True;
    Chart[i].Marks.Font.Color:=clWhite;
    Chart[i].Marks.Font.Name:='Verdana';
    Chart[i].Marks.Font.Size:=9;
  end;

  //Export theme
  SaveTeeToFile(Chart1, SourceFolder + 'TeeAndrosTheme.tee');

Existing series in the chart can be switched to TThemedSeries using the self-explanatory ChangeSeriesType method.

Once the custom custom .tee templates are ready, they can be applied using TThemeList.Apply method from TeeThemes unit, for example:

TThemesList.Apply( DestinationChart, 'MyChart.tee' );

Worth noting that functionality described in this article is intended to be spread across all TeeChart versions in following releases throughout the year so stay tuned as new product updates start rolling out.

Converting VCL/FMX and ActiveX templates to .NET.

Over the years, a number of TeeChart users have asked how to convert the charts they created either using TeeChart VCL/FMX or ActiveX to the .NET version, enabling them to more easily port their previously created charting projects to .NET.

Well, this is possible! It might not be the ideal or perfect solution but it’s an approximation that can save you some work. This can be achieved in two ways:

  1. Using the TeeToTen application. It is a .NET application that uses TeeChart ActiveX to load the .tee files (TeeChart VCL/FMX and ActiveX templates), convert them to text files, generate an XML file with series and data and then load them into a .NET chart  which is then used to generate the .ten file (TeeChart .NET templates) file. The tool comes with a readme.txt document that explains which are its prerequisites and how to use it. TeeToTen tool can also be called via command line with several parameter options. This way it can be called from your applications to obtain a completely automatic conversion. Full details on how to use it are available at included readme.txt.
  2. This solution by-passes the ActiveX version and uses TeeToText, a small VCL application that loads .tee files and generates the necessary text and XML files. Actually, anybody that uses TeeChart VCL/FMX or TeeChart ActiveX can easily generate such files using their built in exporting functionalty, which is what TeeToText does. Once the process is complete,  you need to use TenCreator.dll included with TeeToTen  to import these generated files into your .NET chart. Here’s an example of TenCreator.dll being used to convert one file:
string chartFile = @"C:\temp\TemplateSamples\Annotations.txt";
string dataFile = @"C:\temp\TemplateSamples\Annotations.xml";

TenCreator.TenStreamer streamer = new TenCreator.TenStreamer();
System.IO.Stream netStream = streamer.ConvertFile(chartFile, dataFile);
netStream.Position = 0;
tChart1.Import.Template.Load(netStream);
tChart1.Export.Template.Save(@"C:\TemplateSamples\Annotations.ten");

and here’s an example converting a complete folder:

public Form1()
{
    InitializeComponent();
    InitializeChart();
}

private void InitializeChart()
{
    DirectoryInfo dFolder = new DirectoryInfo(@"C:\TemplateSamples");
    SearchOption so = new SearchOption();
    bool incSubDirectories = false;

    if (incSubDirectories)
    {
        so = SearchOption.AllDirectories;
    }
    else
    {
        so = SearchOption.TopDirectoryOnly;
    }

    FileInfo[] fFileArray = dFolder.GetFiles("*.tee", so);

    foreach (FileInfo fFile in fFileArray)
    {
        ConvertFile(fFile.FullName);
    }
}

private void ConvertFile(string fileName)
{
    string chartFile = fileName.Replace(".tee", ".txt");
    string dataFile = fileName.Replace(".tee", ".xml");

    TenCreator.TenStreamer streamer = new TenCreator.TenStreamer();
    Stream netStream = streamer.ConvertFile(chartFile, dataFile);
    netStream.Position = 0;
    tChart1.Import.Template.Load(netStream);
    tChart1.Export.Template.Save(fileName.Replace(".tee", ".ten"));
}

This project is a work in progress. It’s being improved upon user demand so feel free to let us know your feedback at info at steema dot com.  We hope this helps in the transition of your existing projects that use TeeChart to the .NET platform.