How to: Custom Draw Series
- 6 minutes to read
This example demonstrates one of several possible ways of using the ChartControl.CustomDrawSeries event. In the sample, the event is used to draw custom legend markers for a series.
A custom legend marker is set to the CustomDrawSeriesEventArgsBase.LegendMarkerImage property. Note that in this case, the CustomDrawSeriesEventArgsBase.DisposeLegendMarkerImage property should be set to true to avoid memory leaks.
To customize options used to draw the series point, cast CustomDrawSeriesEventArgsBase.SeriesDrawOptions to the DrawOptions class descendant that stores draw options of the required series view type.
Note
A complete sample project is available at https://github.com/DevExpress-Examples/how-to-draw-a-custom-legend-marker-for-a-series-t332672
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CustomDrawingSample.Model {
public partial class Order {
[Key]
public int OrderID { get; set; }
[Column("EmployeeID")]
[ForeignKey("Employee")]
public int? EmployeeId { get; set; }
[Column("Freight", TypeName = "smallmoney")]
public decimal Freight { get; set; }
[Column("OrderDate", TypeName = "datetime")]
public DateTime OrderDate { get; set; }
public virtual Employee Employee { get; set; }
}
}
namespace CustomDrawingSample.Model {
using System.Data.Entity;
public partial class NwindDbContext : DbContext {
public NwindDbContext()
: base("name=NwindDbContext") {
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
}
}
}
namespace CustomDrawingSample.Model {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Employee
{
[Key]
[Column("EmployeeID")]
public int EmployeeId { get; set; }
[Required]
[StringLength(20)]
public string LastName { get; set; }
[Required]
[StringLength(10)]
public string FirstName { get; set; }
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
virtual public ICollection<Order> Orders { get; set; }
public string FullName {
get { return String.Format("{0} {1}", FirstName, LastName); }
}
}
}
using CustomDrawingSample.Model;
using DevExpress.XtraCharts;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace CustomDrawingSample {
public partial class Form1 : Form {
string trackedSeriesName;
Dictionary<string, Image> photoCache = new Dictionary<string, Image>();
#region #Constants
const int borderSize = 5;
const int scaledPhotoWidth = 48;
const int scaledPhotoHeight = 51;
// Width and height of scaled photo with border.
const int totalWidth = 58;
const int totalHeight = 61;
// Rects required to create a custom legend series marker.
static readonly Rectangle photoRect = new Rectangle(
borderSize, borderSize,
scaledPhotoWidth, scaledPhotoHeight);
static readonly Rectangle totalRect = new Rectangle(
0, 0,
totalWidth, totalHeight);
#endregion
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using (var context = new NwindDbContext()) {
InitPhotoCache(context.Employees);
chart.DataSource = context.Orders.ToList();
}
chart.SeriesDataMember = "Employee.FullName";
chart.SeriesTemplate.ArgumentDataMember = "OrderDate";
chart.SeriesTemplate.ValueDataMembers.AddRange("Freight");
XYDiagram diagram = chart.Diagram as XYDiagram;
if (diagram != null) {
diagram.AxisX.DateTimeScaleOptions.AggregateFunction = AggregateFunction.Sum;
diagram.AxisX.DateTimeScaleOptions.MeasureUnit = DateTimeMeasureUnit.Year;
}
chart.CustomDrawSeries += OnCustomDrawSeries;
chart.ObjectHotTracked += OnObjectHotTracked;
}
private void OnObjectHotTracked(object sender, HotTrackEventArgs e) {
trackedSeriesName = e.HitInfo.InSeries ? ((Series)e.HitInfo.Series).Name : null;
}
void InitPhotoCache(IEnumerable<Employee> employees) {
photoCache.Clear();
foreach (var employee in employees) {
MemoryStream stream = new MemoryStream(employee.Photo);
if (!photoCache.ContainsKey(employee.FullName))
photoCache.Add(employee.FullName, Image.FromStream(stream));
}
}
#region #CustomDrawSeriesImplementation
private void OnCustomDrawSeries(object sender, CustomDrawSeriesEventArgs e) {
bool isSelected = e.Series.Name.Equals(trackedSeriesName);
// Design a series marker image.
Bitmap image = new Bitmap(totalWidth, totalHeight);
using (Graphics graphics = Graphics.FromImage(image)) {
Brush fillBrush = isSelected ?
(Brush)new HatchBrush(HatchStyle.DarkDownwardDiagonal, e.LegendDrawOptions.Color, e.LegendDrawOptions.ActualColor2) :
(Brush)new SolidBrush(e.LegendDrawOptions.Color);
graphics.FillRectangle(fillBrush, totalRect);
Image photo;
if (photoCache.TryGetValue(e.Series.Name, out photo))
graphics.DrawImage(photo, photoRect);
}
e.LegendMarkerImage = image;
e.DisposeLegendMarkerImage = true;
BarDrawOptions options = e.SeriesDrawOptions as BarDrawOptions;
if (options != null && isSelected) {
options.FillStyle.FillMode = DevExpress.XtraCharts.FillMode.Hatch;
((HatchFillOptions)options.FillStyle.Options).HatchStyle = HatchStyle.DarkDownwardDiagonal;
}
}
#endregion
}
}
Imports System.Data.Entity
Namespace CustomDrawingSample.Model
Partial Public Class NwindDbContext
Inherits DbContext
Public Sub New()
MyBase.New("name=NwindDbContext")
End Sub
Public Overridable Property Employees() As DbSet(Of Employee)
Public Overridable Property Orders() As DbSet(Of Order)
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)
End Sub
End Class
End Namespace
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.ComponentModel.DataAnnotations
Imports System.Collections.Generic
Imports System
Namespace CustomDrawingSample.Model
Partial Public Class Employee
<Key, Column("EmployeeID")> _
Public Property EmployeeId() As Integer
<Required, StringLength(20)> _
Public Property LastName() As String
<Required, StringLength(10)> _
Public Property FirstName() As String
<Column(TypeName := "image")> _
Public Property Photo() As Byte()
Public Overridable Property Orders() As ICollection(Of Order)
Public ReadOnly Property FullName() As String
Get
Return String.Format("{0} {1}", FirstName, LastName)
End Get
End Property
End Class
End Namespace
Imports System
Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Namespace CustomDrawingSample.Model
Partial Public Class Order
<Key> _
Public Property OrderID() As Integer
<Column("EmployeeID"), ForeignKey("Employee")> _
Public Property EmployeeId() As Integer?
<Column("Freight", TypeName := "smallmoney")> _
Public Property Freight() As Decimal
<Column("OrderDate", TypeName := "datetime")> _
Public Property OrderDate() As Date
Public Overridable Property Employee() As Employee
End Class
End Namespace
Imports CustomDrawingSample.Model
Imports DevExpress.XtraCharts
Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.IO
Imports System.Linq
Imports System.Windows.Forms
Namespace CustomDrawingSample
Partial Public Class Form1
Inherits Form
Private trackedSeriesName As String
Private photoCache As New Dictionary(Of String, Image)()
#Region "#Constants"
Private Const borderSize As Integer = 5
Private Const scaledPhotoWidth As Integer = 48
Private Const scaledPhotoHeight As Integer = 51
' Width and height of scaled photo with border.
Private Const totalWidth As Integer = 58
Private Const totalHeight As Integer = 61
' Rects required to create a custom legend series marker.
Private Shared ReadOnly photoRect As New Rectangle(borderSize, borderSize, scaledPhotoWidth, scaledPhotoHeight)
Private Shared ReadOnly totalRect As New Rectangle(0, 0, totalWidth, totalHeight)
#End Region
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Using context = New NwindDbContext()
InitPhotoCache(context.Employees)
chart.DataSource = context.Orders.ToList()
End Using
chart.SeriesDataMember = "Employee.FullName"
chart.SeriesTemplate.ArgumentDataMember = "OrderDate"
chart.SeriesTemplate.ValueDataMembers.AddRange("Freight")
Dim diagram As XYDiagram = TryCast(chart.Diagram, XYDiagram)
If diagram IsNot Nothing Then
diagram.AxisX.DateTimeScaleOptions.AggregateFunction = AggregateFunction.Sum
diagram.AxisX.DateTimeScaleOptions.MeasureUnit = DateTimeMeasureUnit.Year
End If
AddHandler chart.CustomDrawSeries, AddressOf OnCustomDrawSeries
AddHandler chart.ObjectHotTracked, AddressOf OnObjectHotTracked
End Sub
Private Sub OnObjectHotTracked(ByVal sender As Object, ByVal e As HotTrackEventArgs)
trackedSeriesName = If(e.HitInfo.InSeries, CType(e.HitInfo.Series, Series).Name, Nothing)
End Sub
Private Sub InitPhotoCache(ByVal employees As IEnumerable(Of Employee))
photoCache.Clear()
For Each employee In employees
Dim stream As New MemoryStream(employee.Photo)
If Not photoCache.ContainsKey(employee.FullName) Then
photoCache.Add(employee.FullName, Image.FromStream(stream))
End If
Next employee
End Sub
#Region "#CustomDrawSeriesImplementation"
Private Sub OnCustomDrawSeries(ByVal sender As Object, ByVal e As CustomDrawSeriesEventArgs)
Dim isSelected As Boolean = e.Series.Name.Equals(trackedSeriesName)
' Design a series marker image.
Dim image As New Bitmap(totalWidth, totalHeight)
Using graphics As Graphics = System.Drawing.Graphics.FromImage(image)
Dim fillBrush As Brush = If(isSelected, CType(New HatchBrush(HatchStyle.DarkDownwardDiagonal, e.LegendDrawOptions.Color, e.LegendDrawOptions.ActualColor2), Brush), CType(New SolidBrush(e.LegendDrawOptions.Color), Brush))
graphics.FillRectangle(fillBrush, totalRect)
Dim photo As Image = Nothing
If photoCache.TryGetValue(e.Series.Name, photo) Then
graphics.DrawImage(photo, photoRect)
End If
End Using
e.LegendMarkerImage = image
e.DisposeLegendMarkerImage = True
Dim options As BarDrawOptions = TryCast(e.SeriesDrawOptions, BarDrawOptions)
If options IsNot Nothing AndAlso isSelected Then
options.FillStyle.FillMode = DevExpress.XtraCharts.FillMode.Hatch
CType(options.FillStyle.Options, HatchFillOptions).HatchStyle = HatchStyle.DarkDownwardDiagonal
End If
End Sub
#End Region
End Class
End Namespace