/// <summary> /// Layout all legned items. /// </summary> public virtual void MeasureSize(DrawingContext dc, Rectangle parentClientRect) { var ds = Chart.DataSource; if (ds == null) { return; } int count = SymbolCount; Children.Clear(); RGFloat maxSymbolWidth = 0, maxSymbolHeight = 0, maxLabelWidth = 0, maxLabelHeight = 0; // Suppress the legend when it has no labels or just repeats the chart title if (count == 1 && string.IsNullOrEmpty(Chart.Title) && GetSymbolText(0) == Chart.GetDisplayTitle()) { return; } #region Measure Sizes for (int index = 0; index < count; index++) { string label = GetSymbolText(index); if (string.IsNullOrEmpty(label)) { continue; } var symbolSize = GetSymbolSize(index); if (maxSymbolWidth < symbolSize.Width) { maxSymbolWidth = symbolSize.Width; } if (maxSymbolHeight < symbolSize.Height) { maxSymbolHeight = symbolSize.Height; } var legendItem = new ChartLegendItem(Chart.DataSerialStyles[index], label) { FontName = FontName, FontSize = FontSize, FontStyles = FontStyles, SymbolBounds = new Rectangle(new Point(0, 0), symbolSize), }; var labelSize = PlatformUtility.MeasureText(dc, label, legendItem.FontName, legendItem.FontSize, legendItem.FontStyles); if (maxLabelWidth < labelSize.Width) { maxLabelWidth = labelSize.Width; } if (maxLabelHeight < labelSize.Height) { maxLabelHeight = labelSize.Height; } legendItem.LabelBounds = new Rectangle(new Point(0, 0), labelSize); Children.Add(legendItem); } #endregion // Measure Sizes #region Layout const RGFloat symbolLabelSpacing = 4; var itemWidth = maxSymbolWidth + symbolLabelSpacing + maxLabelWidth; var itemHeight = Math.Max(maxSymbolHeight, maxLabelHeight); var clientRect = parentClientRect; RGFloat x = 0, y = 0, right = 0, bottom = 0, overflow = 0; if (LegendPosition == LegendPosition.Top || LegendPosition == LegendPosition.Bottom) { overflow = clientRect.Width - itemWidth; } foreach (var item in Children) { if (item is ChartLegendItem legendItem) { legendItem.SetSymbolLocation(0, (itemHeight - legendItem.SymbolBounds.Height) / 2); legendItem.SetLabelLocation(maxSymbolWidth + symbolLabelSpacing, (itemHeight - legendItem.LabelBounds.Height) / 2); legendItem.Bounds = new Rectangle(x, y, itemWidth, itemHeight); if (right < legendItem.Right) { right = legendItem.Right; } if (bottom < legendItem.Bottom) { bottom = legendItem.Bottom; } } const RGFloat itemSpacing = 10; x += itemWidth + itemSpacing; if (x > overflow) { x = 0; y += itemHeight + itemSpacing; } } #endregion // Layout layoutedSize = new Size(right + 10, bottom); }