public TextElementState(TextElementState existing, TextElement element, RenderContext context) { props = element.Props; format = existing?.format ?? new SharpDX.DirectWrite.TextFormat(Renderer.AssertRendererType(context.Renderer).fontFactory, "Times New Roman", 18); layout = new SharpDX.DirectWrite.TextLayout(Renderer.AssertRendererType(context.Renderer).fontFactory, element.Props.Text, format, context.Bounds.Width, context.Bounds.Height); textBrush = existing?.textBrush ?? new SharpDX.Direct2D1.SolidColorBrush(Renderer.AssertRendererType(context.Renderer).d2dTarget, new RawColor4(1, 1, 1, 1)); BoundingBox = new Bounds(x: context.Bounds.X, y: context.Bounds.Y, width: (int)layout.Metrics.Width, height: (int)layout.Metrics.Height); context.Disposables.Add(format); context.Disposables.Add(layout); context.Disposables.Add(textBrush); var childStates = new List <IElementState>(); foreach (var child in element.Children) { var locations = layout.HitTestTextRange(child.Location.StartIndex, child.Location.EndIndex - child.Location.StartIndex, BoundingBox.X, BoundingBox.Y); if (locations.Length == 0) { continue; } var location = locations[0]; childStates.Add(child.Child.Update(null, context.WithBounds(new Bounds(x: (int)location.Left, y: (int)location.Top, width: (int)location.Width, height: (int)location.Height)))); } children = childStates; }
private void DrawString(string text, SimpleFont font, DXMediaBrush brush, double pointX, double pointY, DXMediaBrush areaBrush) { SharpDX.DirectWrite.TextFormat textFormat = font.ToDirectWriteTextFormat(); SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, text, textFormat, ChartPanel.X + ChartPanel.W, textFormat.FontSize); float newW = textLayout.Metrics.Width; float newH = textLayout.Metrics.Height; SharpDX.Vector2 TextPlotPoint = new System.Windows.Point(pointX - newW, pointY - textLayout.Metrics.Height / 2 - 1).ToVector2(); SharpDX.RectangleF PLBoundRect = new SharpDX.RectangleF((float)pointX - newW - 4, (float)pointY - textLayout.Metrics.Height / 2 - 1, newW + 6, newH + 2); SharpDX.Direct2D1.RoundedRectangle PLRoundedRect = new SharpDX.Direct2D1.RoundedRectangle(); PLRoundedRect.RadiusX = newW / 4; PLRoundedRect.RadiusY = newH / 4; PLRoundedRect.Rect = PLBoundRect; RenderTarget.FillRoundedRectangle(PLRoundedRect, areaBrush.DxBrush); RenderTarget.DrawTextLayout(TextPlotPoint, textLayout, brush.DxBrush, SharpDX.Direct2D1.DrawTextOptions.NoSnap); textLayout.Dispose(); textLayout = null; textFormat.Dispose(); textFormat = null; }
protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { // Create a Font, Brush and TextFormat to draw our text. // For more information on drawing Text, please see the source code for the Text DrawingTool var font = new Gui.Tools.SimpleFont("Arial", 20); SharpDX.Direct2D1.Brush tmpBrush = Brushes.Red.ToDxBrush(RenderTarget); SharpDX.DirectWrite.TextFormat textFormat = font.ToDirectWriteTextFormat(); // Create a TextLayout for our text to draw. var cachedTextLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, "Hello, I am sideways text.", textFormat, 600, textFormat.FontSize); // Rotate the RenderTarget by setting the Matrix3x2 Transform property // Matrix3x2.Rotation() will return a rotated Matrix3x2 based off of the angle specified, and the center point where you draw the object RenderTarget.Transform = Matrix3x2.Rotation(1.5708f, new Vector2(100, 100)); // Draw the text on the rotated RenderTarget RenderTarget.DrawTextLayout(new SharpDX.Vector2(100, 100), cachedTextLayout, tmpBrush, SharpDX.Direct2D1.DrawTextOptions.NoSnap); // Dispose of resources textFormat.Dispose(); cachedTextLayout.Dispose(); tmpBrush.Dispose(); // Rotate the RenderTarget back RenderTarget.Transform = Matrix3x2.Identity; // Return rendering to base class base.OnRender(chartControl, chartScale); }
public void RenderTextOffscreen(string text) { // Clear the off-screen render target. deviceResources.D3DDeviceContext.ClearRenderTargetView(renderTargetView, new RawColor4(0f, 0f, 0f, 0f)); // Begin drawing with D2D. d2dRenderTarget.BeginDraw(); // Create a text layout to match the screen. SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(deviceResources.DWriteFactory, text, textFormat, textureWidth, textureHeight); // Get the text metrics from the text layout. SharpDX.DirectWrite.TextMetrics metrics = textLayout.Metrics; // In this example, we position the text in the center of the off-screen render target. Matrix3x2 screenTranslation = Matrix3x2.CreateTranslation( textureWidth * 0.5f, textureHeight * 0.5f + metrics.Height * 0.5f ); whiteBrush.Transform = screenTranslation.ToRawMatrix3x2(); // Render the text using DirectWrite. d2dRenderTarget.DrawTextLayout(new RawVector2(), textLayout, whiteBrush); // End drawing with D2D. d2dRenderTarget.EndDraw(); }
private void UpdateTextLayout(float maxWidth) { if (!needsLayoutUpdate) { return; } needsLayoutUpdate = false; cachedTextLayout = null; if (Font == null) { return; } SharpDX.DirectWrite.TextFormat textFormat = Font.ToDirectWriteTextFormat(); cachedTextLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, DisplayText ?? string.Empty, textFormat, maxWidth, textFormat.FontSize); // again, make sure to chop max width/height to only amount actually needed cachedTextLayout.MaxWidth = cachedTextLayout.Metrics.Width; cachedTextLayout.MaxHeight = cachedTextLayout.Metrics.Height; // NOTE: always use leading alignment since our layout box will be the size of the text (http://i.msdn.microsoft.com/dynimg/IC520425.png) cachedTextLayout.TextAlignment = Alignment == TextAlignment.Center ? SharpDX.DirectWrite.TextAlignment.Center : Alignment == TextAlignment.Right ? SharpDX.DirectWrite.TextAlignment.Trailing : SharpDX.DirectWrite.TextAlignment.Leading; needsLayoutUpdate = false; textFormat.Dispose(); }
public CommonSize MeasureStringSize(object graphics, FontType font, string text) { var isGdi = graphics is Graphics; var sizeCache = (isGdi ? gdiSizeCaches : dwSizeCaches).GetOrAdd(font, f => { int lineHeight; if (isGdi) { lineHeight = TextRenderer.MeasureText((Graphics)graphics, "X", Fonts.GetFont(font), Size.Empty, App.DefaultTextFormatFlags).Height; } else { using (var layout = new SharpDX.DirectWrite.TextLayout(Fonts.Factory, "X", Fonts.GetTextFormat(font), 1000000, 1000000)) { var metrics = layout.Metrics; lineHeight = (int)metrics.Height; //lineHeight = (int)Math.Ceiling(Fonts.GetTextFormat(font).FontSize); } } return(Tuple.Create(new ConcurrentDictionary <string, CommonSize>(), new ConcurrentStack <string>(), lineHeight)); }); return(sizeCache.Item1.GetOrAdd(text, s => { if (sizeCache.Item2.Count >= sizeCacheStackLimit) { string value; if (sizeCache.Item2.TryPop(out value)) { CommonSize _s; sizeCache.Item1.TryRemove(value, out _s); } } sizeCache.Item2.Push(s); if (isGdi) { var size = TextRenderer.MeasureText((IDeviceContext)graphics, text, Fonts.GetFont(font), Size.Empty, App.DefaultTextFormatFlags); return new CommonSize(size.Width, sizeCache.Item3); } else { try { using (var layout = new SharpDX.DirectWrite.TextLayout(Fonts.Factory, text, Fonts.GetTextFormat(font), 1000000, 1000000)) { var metrics = layout.Metrics; return new CommonSize((int)metrics.WidthIncludingTrailingWhitespace, sizeCache.Item3); } } catch { } return new CommonSize(100, 10); } })); }
protected override void OnStateChange() { base.OnStateChange(); if (State == State.SetDefaults) { Name = "Labeled Line"; OutlineStroke = new Stroke(Brushes.Black, 2f); BackgroundBrush = Brushes.Black; OffScreenBrush = Brushes.Red; DisplayText = String.Empty; AppendPriceTime = true; Font = null; AreaOpacity = 75; TextDisplayMode = TextMode.EndPointAtPriceScale; HorizontalOffset = 0.5; VerticalOffset = 3; offScreenDXBrushNeedsUpdate = true; backgroundDXBrushNeedsUpdate = true; } else if (State == State.Terminated) { if (cachedTextLayout != null) { cachedTextLayout.Dispose(); } cachedTextLayout = null; } }
private void HandleDrawString(RenderTarget target, String str, System.Drawing.Rectangle rect, int color, System.Drawing.Font font = null) { if (String.IsNullOrEmpty(str)) { return; } using (Brush brush = GetBrushFromColor(target, color)) { SharpDX.DirectWrite.FontWeight weight = WeightFromFontStyle(font.Style); SharpDX.DirectWrite.FontStyle style = StyleFromFontStyle(font.Style); SharpDX.DirectWrite.TextFormat stringFormat = new SharpDX.DirectWrite.TextFormat(this.FactoryDWrite, font.FontFamily.Name, weight, style, font.Size); stringFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading; stringFormat.WordWrapping = SharpDX.DirectWrite.WordWrapping.Wrap; if (font == null) { font = this.Font; } int maxsize = this.Width; if (pushedArgument.ContainsKey("TrimOutOfBounds") && ((bool)pushedArgument["TrimOutOfBounds"])) { using (SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(FactoryDWrite, str, stringFormat, maxsize, font.Height)) { var lines = layout.GetLineMetrics(); StringBuilder strb = new StringBuilder(); var hittests = layout.HitTestTextRange(0, str.Length, rect.X, rect.Y); int trimPos = -1; for (int i = 0; i < hittests.Length; ++i) { if (hittests[i].Top + hittests[i].Height > rect.Bottom) { trimPos = hittests[i].TextPosition; break; } } String trimmedStr = str; if (trimPos > -1) { trimmedStr = str.Substring(0, trimPos); } target.PushAxisAlignedClip(new RectangleF(rect.X, rect.Y, rect.Right, rect.Bottom), AntialiasMode.Aliased); target.DrawText(trimmedStr, stringFormat, new RawRectangleF(rect.X, rect.Y, rect.Right, rect.Bottom), brush, DrawTextOptions.EnableColorFont | DrawTextOptions.Clip); target.PopAxisAlignedClip(); } } else { target.PushAxisAlignedClip(new RectangleF(rect.X, rect.Y, rect.Right, rect.Bottom), AntialiasMode.Aliased); target.DrawText(str, stringFormat, new RawRectangleF(rect.X, rect.Y, rect.Right, rect.Bottom), brush, DrawTextOptions.EnableColorFont | DrawTextOptions.Clip); target.PopAxisAlignedClip(); } stringFormat.Dispose(); } }
public SizeF MeasureString(string text, DUIFont font, float width, float height) { using (SharpDX.DirectWrite.TextLayout tl = DxConvert.ToTextLayout(font, text)) { float w = tl.Metrics.WidthIncludingTrailingWhitespace; float h = tl.Metrics.Height; return(new SizeF(w, h)); } }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Isolated); SharpDX.DirectWrite.TextFormat textFormat = new SharpDX.DirectWrite.TextFormat(factory, "Arial", 60); textLayout = new SharpDX.DirectWrite.TextLayout(factory, "Test", textFormat, 0, 0); MainWindow_SizeChanged(null, null); InteropImage.WindowOwner = (new System.Windows.Interop.WindowInteropHelper(this)).Handle; InteropImage.OnRender = OnRender; CompositionTarget.Rendering += CompositionTarget_Rendering; }
private void Init() { Color = Base.Brushes.GetColor(Settings.Colors.PidBox); var text = new SharpDX.DirectWrite.TextLayout(Base.DWFactory, "999 FPS", Base.DefaultTextFormat, Screen.ScreenSize.Width, Screen.ScreenSize.Height); if (Math.Round(text.Metrics.Width) != text.Metrics.Width) { Debug.WriteLine("Text metrics produce float values"); } Size = new RawVector2(text.Metrics.Width + 2, text.Metrics.Height + 2); text.Dispose(); }
private void RenderText(float textX, float textY, string text, Brush brush) { if (ChartControl == null) { return; } using (SharpDX.DirectWrite.TextFormat textFormat = ChartControl.Properties.LabelFont.ToDirectWriteTextFormat()) { using (SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, text, textFormat, ChartPanel.W, 8f)) { SharpDX.Vector2 origin = new SharpDX.Vector2(textX, textY - (float)(textLayout.Metrics.Height * 2.5)); // bump above copyright RenderTarget.DrawTextLayout(origin, textLayout, brush.ToDxBrush(RenderTarget)); } } }
public void Apply(TextLayout layout) { if (Enabled) { var factory = FontWrapperFactory.GetFactory(); var sc = this.Color; SharpDX.Color4 c = *(SharpDX.Color4 *) & sc; colorStyle = factory.CreateColor(c); SharpDX.DirectWrite.TextLayout tl = new SharpDX.DirectWrite.TextLayout(layout.ComPointer); tl.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(Range.StartPosition, Range.Length)); Marshal.Release(colorStyle.NativePointer); } }
public override void OnMouseMove(ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale, ChartAnchor dataPoint) { if (IsLocked && DrawingState != DrawingState.Building) { return; } if (DrawingState == DrawingState.Building) { // start anchor will not be editing here because we start building as soon as user clicks, which // plops down a start anchor right away. check these seperately because they will both initially // be in edit mode. if (EndAnchor.IsEditing) { dataPoint.CopyDataValues(EndAnchor); dataPoint.CopyDataValues(TextAnchor); isTextCreated = false; } else if (TextAnchor.IsEditing) { dataPoint.CopyDataValues(TextAnchor); } } else if (DrawingState == DrawingState.Editing && editingAnchor != null) { dataPoint.CopyDataValues(editingAnchor); if (editingAnchor == StartAnchor || editingAnchor == EndAnchor) { isTextCreated = false; } } else if (DrawingState == DrawingState.Moving) { foreach (ChartAnchor anchor in Anchors) { anchor.MoveAnchor(InitialMouseDownAnchor, dataPoint, chartControl, chartPanel, chartScale, this); } // dont forget to update delta to last used if (textLayout != null) { textLayout.Dispose(); } textLayout = null; } }
protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { /// get the starting and ending bars from what is rendered on the chart float startX = chartControl.GetXByBarIndex(ChartBars, ChartBars.FromIndex); float endX = chartControl.GetXByBarIndex(ChartBars, ChartBars.ToIndex); /// Loop through each Plot Values on the chart for (int seriesCount = 0; seriesCount < Values.Length; seriesCount++) { /// get the value at the last bar on the chart (if it has been set) if (Values[seriesCount].IsValidDataPointAt(ChartBars.ToIndex)) { double plotValue = Values[seriesCount].GetValueAt(ChartBars.ToIndex); /// convert the plot value to the charts "Y" axis point float chartScaleYValue = chartScale.GetYByValue(plotValue); /// calculate the x and y values for the line to start and end SharpDX.Vector2 startPoint = new SharpDX.Vector2(startX, chartScaleYValue); SharpDX.Vector2 endPoint = new SharpDX.Vector2(endX, chartScaleYValue); /// draw a line between the start and end point at each plot using the plots SharpDX Brush color and style RenderTarget.DrawLine(startPoint, endPoint, Plots[seriesCount].BrushDX, Plots[seriesCount].Width, Plots[seriesCount].StrokeStyle); /// use the chart control text form to draw plot values along the line SharpDX.DirectWrite.TextFormat textFormat = chartControl.Properties.LabelFont.ToDirectWriteTextFormat(); /// calculate the which will be rendered at each plot using it the plot name and its price string textToRender = Plots[seriesCount].Name + ": " + plotValue; /// calculate the layout of the text to be drawn SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, textToRender, textFormat, 200, textFormat.FontSize); /// draw a line at each plot using the plots SharpDX Brush color at the calculated start point RenderTarget.DrawTextLayout(startPoint, textLayout, Plots[seriesCount].BrushDX); // /// dipose of the unmanaged resources used textLayout.Dispose(); textFormat.Dispose(); } } }
protected override void Dispose(bool disposing) { base.Dispose(disposing); if (cachedTextLayout != null) { cachedTextLayout.Dispose(); } if (textBrushDevice != null) { textBrushDevice.RenderTarget = null; } if (areaBrushDevice != null) { areaBrushDevice.RenderTarget = null; } cachedTextLayout = null; textBrushDevice = null; areaBrushDevice = null; }
private void DrawString(string text, SimpleFont font, string brushName, double pointX, double pointY, string areaBrushName) { SharpDX.DirectWrite.TextFormat textFormat = font.ToDirectWriteTextFormat(); SharpDX.Vector2 TextPlotPoint = new System.Windows.Point(pointX, pointY).ToVector2(); SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, text, textFormat, ChartPanel.X + ChartPanel.W, textFormat.FontSize); float newW = textLayout.Metrics.Width; float newH = textLayout.Metrics.Height; SharpDX.RectangleF PLBoundRect = new SharpDX.RectangleF((float)pointX + 2, (float)pointY, newW + 5, newH + 2); RenderTarget.FillRectangle(PLBoundRect, dxmBrushes[areaBrushName].DxBrush); RenderTarget.DrawTextLayout(TextPlotPoint, textLayout, dxmBrushes[brushName].DxBrush, SharpDX.Direct2D1.DrawTextOptions.NoSnap); textLayout.Dispose(); textFormat.Dispose(); }
public System.Drawing.SizeF MeasureString(String s, System.Drawing.Font font = null, int maxsize = -1) { if (font == null) { font = this.Font; } using (SharpDX.DirectWrite.TextFormat format = new SharpDX.DirectWrite.TextFormat(FactoryDWrite, font.FontFamily.Name, WeightFromFontStyle(font.Style), StyleFromFontStyle(font.Style), font.Size)) { if (maxsize == -1) { maxsize = this.Width; } format.WordWrapping = SharpDX.DirectWrite.WordWrapping.Wrap; using (SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(FactoryDWrite, s, format, maxsize, font.Height)) { return(new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height)); } } }
public void Apply(TextLayout layout) { if (Enabled) { var sc = this.Color; SharpDX.Color4 c = *(SharpDX.Color4 *) & sc; if (colorStyle == null) { var factory = FontWrapperFactory.GetFactory(); colorStyle = factory.CreateColor(c); } else { colorStyle.SetColor(c.Red, c.Green, c.Blue, c.Alpha); } SharpDX.DirectWrite.TextLayout tl = new SharpDX.DirectWrite.TextLayout(layout.ComPointer); tl.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(Range.StartPosition, Range.Length)); } }
protected void DrawPriceLevelText(double minX, double maxX, Point endPoint, PriceLevel priceLevel, ChartPanel panel) { Gui.Tools.SimpleFont wpfFont = panel.ChartControl.Properties.LabelFont ?? new Gui.Tools.SimpleFont(); SharpDX.DirectWrite.TextFormat dxTextFormat = wpfFont.ToDirectWriteTextFormat(); string str = string.Format("{0}", (priceLevel.Value / 100).ToString("P")); SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, str, dxTextFormat, panel.H, dxTextFormat.FontSize); float usedFontHeight = textLayout.Metrics.Height; float usedFontWidth = textLayout.Metrics.Width; Point textEndPoint = endPoint; double maxWidth = panel.X + panel.W; double maxHeight = panel.Y + panel.H; double minWidth = panel.X; double minHeight = panel.Y; if (textEndPoint.Y + usedFontHeight >= maxHeight) { textEndPoint.Y = maxHeight - usedFontHeight; // Set to bottom } if (textEndPoint.Y < minHeight) // Set to top { textEndPoint.Y = minHeight; } if (textEndPoint.X + usedFontWidth >= maxWidth) { textEndPoint.X = maxWidth - usedFontWidth; //Set to right side; } if (textEndPoint.X < minWidth) { textEndPoint.X = minWidth; // Set to left side; } RenderTarget.DrawTextLayout(new SharpDX.Vector2((float)(textEndPoint.X), (float)(textEndPoint.Y)), textLayout, priceLevel.Stroke.BrushDX, SharpDX.Direct2D1.DrawTextOptions.NoSnap); dxTextFormat.Dispose(); textLayout.Dispose(); }
public void DrawText(string Text, System.Drawing.Rectangle drawRectangle, System.Drawing.Color Color, System.Drawing.Font Font, bool overflowHidden = true) { float width = drawRectangle.Width; float height = drawRectangle.Height; if (overflowHidden) { SharpDX.DirectWrite.TextLayout pTextLayout = new SharpDX.DirectWrite.TextLayout( DWrender, Text, utils.Font2Raw(Font), drawRectangle.Width, drawRectangle.Height); width = pTextLayout.Metrics.WidthIncludingTrailingWhitespace; height = pTextLayout.Metrics.Height; } if (width < drawRectangle.Width && height < drawRectangle.Height) { D2Drender.DrawText(Text, utils.Font2Raw(Font), utils.Retangle2Raw(drawRectangle), utils.SoildBrush2Raw(Color)); } }
protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @""; Name = "SymbolWatermark"; IsOverlay = true; IsSuspendedWhileInactive = true; FontSize = 160f; TextBrush = Brushes.Gray; TextOpacity = 30; } else if (State == State.Configure) { SetZOrder(-100); } else if (State == State.DataLoaded) { SetOpacity(); startPoint = new SharpDX.Vector2(); endPoint = new SharpDX.Vector2(); // use the chart control text label font information when creating our object SharpDX.DirectWrite.TextFormat chartTextFormat = ChartControl.Properties.LabelFont.ToDirectWriteTextFormat(); // create a new TextFormat object using information from the chart labels SharpDX.DirectWrite.TextFormat textFormat = new SharpDX.DirectWrite.TextFormat(Core.Globals.DirectWriteFactory, chartTextFormat.FontFamilyName, chartTextFormat.FontWeight, chartTextFormat.FontStyle, FontSize); // calculate the layout of the text to be drawn string fullName = Instrument.FullName; var digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' }; var shortName = fullName.TrimEnd(digits); textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, shortName, textFormat, 1000, textFormat.FontSize); } }
private void DrawPriceText(ChartAnchor anchor, Point point, double price, ChartControl chartControl, ChartPanel chartPanel, ChartScale chartScale) { if (TextAlignment == TextLocation.Off) { return; } string priceString; ChartBars chartBars = GetAttachedToChartBars(); // bars can be null while chart is initializing if (chartBars == null) { return; } priceString = GetPriceString(price, chartBars); Stroke color; textleftPoint = RiskAnchor.GetPoint(chartControl, chartPanel, chartScale).X; textRightPoint = EntryAnchor.GetPoint(chartControl, chartPanel, chartScale).X; if (anchor == RewardAnchor) { color = TargetLineStroke; } else if (anchor == RiskAnchor) { color = StopLineStroke; } else if (anchor == EntryAnchor) { color = EntryLineStroke; } else { color = AnchorLineStroke; } SimpleFont wpfFont = chartControl.Properties.LabelFont ?? new SimpleFont(); SharpDX.DirectWrite.TextFormat textFormat = wpfFont.ToDirectWriteTextFormat(); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading; textFormat.WordWrapping = SharpDX.DirectWrite.WordWrapping.NoWrap; SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, priceString, textFormat, chartPanel.H, textFormat.FontSize); if (RiskAnchor.Time <= EntryAnchor.Time) { if (!IsExtendedLinesLeft && !IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textleftPoint; break; case TextLocation.InsideRight: point.X = textRightPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = textleftPoint; break; case TextLocation.ExtremeRight: point.X = textRightPoint - textLayout.Metrics.Width; break; } } else if (IsExtendedLinesLeft && !IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textleftPoint; break; case TextLocation.InsideRight: point.X = textRightPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = chartPanel.X; break; case TextLocation.ExtremeRight: point.X = textRightPoint - textLayout.Metrics.Width; break; } } else if (!IsExtendedLinesLeft && IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textleftPoint; break; case TextLocation.InsideRight: point.X = textRightPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = textleftPoint; break; case TextLocation.ExtremeRight: point.X = chartPanel.W - textLayout.Metrics.Width; break; } } else if (IsExtendedLinesLeft && IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textleftPoint; break; case TextLocation.InsideRight: point.X = textRightPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeRight: point.X = chartPanel.W - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = chartPanel.X; break; } } } else if (RiskAnchor.Time >= EntryAnchor.Time) { if (!IsExtendedLinesLeft && !IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textRightPoint; break; case TextLocation.InsideRight: point.X = textleftPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = textRightPoint; break; case TextLocation.ExtremeRight: point.X = textleftPoint - textLayout.Metrics.Width; break; } } else if (IsExtendedLinesLeft && !IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textRightPoint; break; case TextLocation.InsideRight: point.X = textleftPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = chartPanel.X; break; case TextLocation.ExtremeRight: point.X = textleftPoint - textLayout.Metrics.Width; break; } } else if (!IsExtendedLinesLeft && IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textRightPoint; break; case TextLocation.InsideRight: point.X = textleftPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = textRightPoint; break; case TextLocation.ExtremeRight: point.X = chartPanel.W - textLayout.Metrics.Width; break; } } else if (IsExtendedLinesLeft && IsExtendedLinesRight) { switch (TextAlignment) { case TextLocation.InsideLeft: point.X = textRightPoint; break; case TextLocation.InsideRight: point.X = textleftPoint - textLayout.Metrics.Width; break; case TextLocation.ExtremeRight: point.X = chartPanel.W - textLayout.Metrics.Width; break; case TextLocation.ExtremeLeft: point.X = chartPanel.X; break; } } } RenderTarget.DrawTextLayout(new SharpDX.Vector2((float)point.X, (float)point.Y), textLayout, color.BrushDX, SharpDX.Direct2D1.DrawTextOptions.NoSnap); }
private static void Main() { RenderForm renderForm = new RenderForm("SharpFontWrapper - Simple Text"); renderForm.Width = 1024; renderForm.Height = 768; viewPort = new ViewportF(0, 0, renderForm.Width, renderForm.Height, 0.0f, 1.0f); device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug); deviceContext = device.ImmediateContext; using (SharpDX.DXGI.Factory dxgiFactory = new SharpDX.DXGI.Factory1()) { SharpDX.DXGI.SwapChainDescription swapChainDesc = new SharpDX.DXGI.SwapChainDescription() { BufferCount = 2, Flags = SharpDX.DXGI.SwapChainFlags.None, IsWindowed = true, ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm), OutputHandle = renderForm.Handle, SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0), SwapEffect = SharpDX.DXGI.SwapEffect.Discard, Usage = SharpDX.DXGI.Usage.BackBuffer | SharpDX.DXGI.Usage.RenderTargetOutput }; swapChain = new SwapChain(dxgiFactory, device, swapChainDesc); using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderView = new RenderTargetView(device, backBuffer); } } fontFactory = new SharpFontWrapper.Factory(); fontWrapper = fontFactory.CreateFontWrapper(device, "Arial"); colorStyle = fontFactory.CreateColor(SharpDX.Color.Green); textFormat = new SharpDX.DirectWrite.TextFormat(fontWrapper.DWriteFactory, "Consolas", 32.0f); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; textFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near; textLayout = new SharpDX.DirectWrite.TextLayout(fontWrapper.DWriteFactory, "DirectWrite Text Layout with formatting and color", textFormat, 1000.0f, 1000.0f); textLayout.SetFontStyle(SharpDX.DirectWrite.FontStyle.Italic, new SharpDX.DirectWrite.TextRange(0, 11)); textLayout.SetFontFamilyName("Arial", new SharpDX.DirectWrite.TextRange(24, 4)); textLayout.SetFontSize(72.0f, new SharpDX.DirectWrite.TextRange(29, 10)); //Stylistic typeography SharpDX.DirectWrite.Typography typoGraphy = new SharpDX.DirectWrite.Typography(fontWrapper.DWriteFactory); typoGraphy.AddFontFeature(new SharpDX.DirectWrite.FontFeature(SharpDX.DirectWrite.FontFeatureTag.StylisticSet7, 1)); textLayout.SetFontFamilyName("Gabriola", new SharpDX.DirectWrite.TextRange(12, 4)); textLayout.SetTypography(typoGraphy, new SharpDX.DirectWrite.TextRange(12, 4)); //Note : to pass color, make sure to use native pointer, as in that case we do not need sharpdx/.net to build com wrapper, colorStyle is already one textLayout.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(44, 5)); RenderLoop.Run(renderForm, () => { float t = (float)watch.Elapsed.TotalMilliseconds; float x = ((float)Math.Sin(t * 0.002f) * 100.0f) + (renderForm.Width * 0.5f); deviceContext.OutputMerger.SetRenderTargets(renderView); deviceContext.Rasterizer.SetViewport(viewPort); deviceContext.ClearRenderTargetView(renderView, Color.Black); SharpFontWrapper.TextFlags flags = SharpFontWrapper.TextFlags.NoWordWrapping | SharpFontWrapper.TextFlags.VerticalCenter | SharpFontWrapper.TextFlags.Center; fontWrapper.DrawString(deviceContext, "Hello SharpFontWrapper", 64.0f, new Vector2(x, renderForm.Height * 0.25f), Color.Yellow, flags); fontWrapper.DrawString(deviceContext, "This is another text", 64.0f, new Vector2(renderForm.Width * 0.5f, renderForm.Height * 0.25f + 100.0f), Color.White, flags); fontWrapper.DrawTextLayout(deviceContext, textLayout, new Vector2(0, renderForm.Height * 0.25f + 200.0f), Color.White, flags); swapChain.Present(1, SharpDX.DXGI.PresentFlags.None); }); typoGraphy.Dispose(); colorStyle.Dispose(); textLayout.Dispose(); textFormat.Dispose(); fontWrapper.Dispose(); fontFactory.Dispose(); deviceContext.ClearState(); deviceContext.Flush(); renderView.Dispose(); swapChain.Dispose(); deviceContext.Dispose(); device.Dispose(); }
public override void Load( CanvasRenderArguments args ) { if ( lineBrush != null && !lineBrush.IsDisposed ) lineBrush.Dispose(); if (DW_textFormat != null && !DW_textFormat.IsDisposed) DW_textFormat.Dispose(); // init the lines brushs lineBrush = new SolidColorBrush( args.renderTarget, _FontColor ); _TextFormat.fontCollection = args.WriteFactory.GetSystemFontCollection(false); // init the text format DW_textFormat = new SharpDX.DirectWrite.TextFormat( args.WriteFactory, _TextFormat.familyName, _TextFormat.fontCollection, _TextFormat.weight, _TextFormat.fontStyle, _TextFormat.fontStretch, _TextFormat.fontSize, "en-us" ); // get the size of the string SharpDX.DirectWrite.TextLayout textL= new SharpDX.DirectWrite.TextLayout( args.WriteFactory, Internal_String, DW_textFormat, 1500, 1500 ); Size = new Vector.FxVector2f(textL.GetFontSize(0) * Internal_String.Length, textL.GetFontSize(0)); textL.Dispose(); // init text rectangle textRectangle = new RectangleF( 0, 0, Size.x, Size.y ); }
public override void OnRender(ChartControl chartControl, ChartScale chartScale) { RenderTarget.AntialiasMode = SharpDX.Direct2D1.AntialiasMode.PerPrimitive; ChartPanel panel = chartControl.ChartPanels[PanelIndex]; Point anchorPoint = Anchor.GetPoint(chartControl, panel, chartScale); Point lastEndPoint = new Point(0, 0); SharpDX.Direct2D1.Brush lastBrush = null; foreach (GannAngle gannAngle in GannAngles.Where(ga => ga.IsVisible && ga.Stroke != null).OrderBy(ga => (ga.RatioX / ga.RatioY))) { gannAngle.Stroke.RenderTarget = RenderTarget; double dx = gannAngle.RatioX * chartControl.Properties.BarDistance; double dVal = gannAngle.RatioY * PointsPerBar; //NT7, just multiple directly this is price not pixels //chartScale.GetPixelsForDistance(gannAngle.RatioY * PointsPerBar); Vector gannDataVector = GetGannStepDataVector(dx, dVal); Point extendedEndPoint = CalculateExtendedDataPoint(panel, chartScale, Convert.ToInt32(anchorPoint.X), Anchor.Price, gannDataVector); // align to full pixel to avoid unneeded aliasing double strokePixAdj = ((double)(gannAngle.Stroke.Width % 2)).ApproxCompare(0) == 0 ? 0.5d : 0d; Vector pixelAdjustVec = new Vector(0, strokePixAdj); SharpDX.Direct2D1.Brush tmpBrush = IsInHitTest ? chartControl.SelectionBrush : gannAngle.Stroke.BrushDX; RenderTarget.DrawLine((anchorPoint + pixelAdjustVec).ToVector2(), (extendedEndPoint + pixelAdjustVec).ToVector2(), tmpBrush, gannAngle.Stroke.Width, gannAngle.Stroke.StrokeStyle); if (lastBrush != null) { float oldOpacity = lastBrush.Opacity; lastBrush.Opacity = PriceLevelOpacity / 100f; // create geometry SharpDX.Direct2D1.PathGeometry lineGeometry = new SharpDX.Direct2D1.PathGeometry(Core.Globals.D2DFactory); SharpDX.Direct2D1.GeometrySink sink = lineGeometry.Open(); sink.BeginFigure(lastEndPoint.ToVector2(), SharpDX.Direct2D1.FigureBegin.Filled); // Does the fill color need to fill a corner? Check and add a point if (Math.Abs(lastEndPoint.Y - extendedEndPoint.Y) > 0.1 && Math.Abs(lastEndPoint.X - extendedEndPoint.X) > 0.1) { double boundaryX; double boundaryY; if (lastEndPoint.Y <= ChartPanel.Y || lastEndPoint.Y >= ChartPanel.Y + ChartPanel.H) { if (FanDirection == GannFanDirection.UpLeft || FanDirection == GannFanDirection.UpRight) { boundaryY = extendedEndPoint.Y; boundaryX = lastEndPoint.X; } else { boundaryY = lastEndPoint.Y; boundaryX = extendedEndPoint.X; } } else { if (FanDirection == GannFanDirection.UpLeft || FanDirection == GannFanDirection.UpRight) { boundaryY = lastEndPoint.Y; boundaryX = extendedEndPoint.X; } else { boundaryY = extendedEndPoint.Y; boundaryX = lastEndPoint.X; } } sink.AddLine(new SharpDX.Vector2((float)boundaryX, (float)boundaryY)); } sink.AddLine(extendedEndPoint.ToVector2()); sink.AddLine((anchorPoint + pixelAdjustVec).ToVector2()); sink.AddLine((lastEndPoint).ToVector2()); sink.EndFigure(SharpDX.Direct2D1.FigureEnd.Closed); sink.Close(); RenderTarget.FillGeometry(lineGeometry, lastBrush); lineGeometry.Dispose(); lastBrush.Opacity = oldOpacity; } lastEndPoint = extendedEndPoint + pixelAdjustVec; lastBrush = tmpBrush; } if (!IsTextDisplayed || IsInHitTest) { return; } foreach (GannAngle gannAngle in GannAngles.Where(ga => ga.IsVisible && ga.Stroke != null).OrderBy(ga => (ga.RatioX / ga.RatioY))) { gannAngle.Stroke.RenderTarget = RenderTarget; double dx = gannAngle.RatioX * chartControl.Properties.BarDistance; double dVal = gannAngle.RatioY * PointsPerBar; //NT7, just multiple directly this is price not pixels //chartScale.GetPixelsForDistance(gannAngle.RatioY * PointsPerBar); Vector gannDataVector = GetGannStepDataVector(dx, dVal); Point extendedEndPoint = CalculateExtendedDataPoint(panel, chartScale, Convert.ToInt32(anchorPoint.X), Anchor.Price, gannDataVector); if (!IsTextDisplayed || IsInHitTest) { continue; } SimpleFont wpfFont = chartControl.Properties.LabelFont ?? new SimpleFont(); SharpDX.DirectWrite.TextFormat textFormat = wpfFont.ToDirectWriteTextFormat(); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading; textFormat.WordWrapping = SharpDX.DirectWrite.WordWrapping.NoWrap; SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, gannAngle.Name, textFormat, 100, textFormat.FontSize); // once text is laid out, update used width to calcuated space required float fontHeight = textLayout.Metrics.Height; Point textEndPoint = new Point(extendedEndPoint.X, extendedEndPoint.Y); if (textEndPoint.X > panel.X + panel.W - textLayout.Metrics.Width) { textEndPoint.X = panel.X + panel.W - textLayout.Metrics.Width; textEndPoint.Y += textLayout.Metrics.Width; } if (gannDataVector.Y > 0) { if (textEndPoint.Y < panel.Y + (fontHeight * 0.5)) { textEndPoint.Y = panel.Y + (fontHeight * 0.5); } } else { if (textEndPoint.Y > panel.Y + panel.H - (fontHeight * 1.5)) { textEndPoint.Y = panel.Y + panel.H - (fontHeight * 1.5); } } float?marginResource = Application.Current.FindResource("FontModalTitleMargin") as float?; float margin = 2f + (marginResource.HasValue ? marginResource.Value : 3f); // Allow for changes in X position based on whether text is aligned to left or right edge of screen float marginX = FanDirection == GannFanDirection.DownLeft || FanDirection == GannFanDirection.UpLeft ? margin : -2 * margin; SharpDX.Vector2 endVec = new SharpDX.Vector2((float)textEndPoint.X, (float)textEndPoint.Y); SharpDX.Matrix3x2 transformMatrix = SharpDX.Matrix3x2.Translation(endVec); RenderTarget.Transform = transformMatrix; RenderTarget.DrawTextLayout(new SharpDX.Vector2(marginX + margin, margin), textLayout, gannAngle.Stroke.BrushDX, SharpDX.Direct2D1.DrawTextOptions.NoSnap); RenderTarget.Transform = SharpDX.Matrix3x2.Identity; textFormat.Dispose(); textLayout.Dispose(); } }
public override void Load( CanvasRenderArguments args ) { // dispose the old brush if (lineBrush != null && !lineBrush.IsDisposed) lineBrush.Dispose(); if (DW_textFormat != null && !DW_textFormat.IsDisposed) DW_textFormat.Dispose(); // init the lines brushs lineBrush = new SolidColorBrush( args.renderTarget, _AxesColor.ToColor4() ); _TextFormat.fontCollection = args.WriteFactory.GetSystemFontCollection(false); // init the text format DW_textFormat = new SharpDX.DirectWrite.TextFormat(args.WriteFactory, _TextFormat.familyName, _TextFormat.fontCollection, _TextFormat.weight, _TextFormat.fontStyle, _TextFormat.fontStretch, _TextFormat.fontSize, "en-us"); // get the size of the string SharpDX.DirectWrite.TextLayout textL = new SharpDX.DirectWrite.TextLayout(args.WriteFactory, "(0,0)", DW_textFormat, 1500, 1500); // init text rectangle textRectangle = new RectangleF(0, 0, textL.GetFontSize(0) * 10, textL.GetFontSize(0)); textL.Dispose(); // refresh the geometrys RefreshGeometry( args.renderTarget ); }
/// <summary> /// Draws the specified text using the format information provided by an SharpDX.DirectWrite.TextFormat object</summary> /// <param name="text">A string to draw</param> /// <param name="textFormat">An object that describes formatting details of the text to draw, such as /// the font, the font size, and flow direction</param> /// <param name="layoutRect">The size and position of the area in which the text is drawn</param> /// <param name="brush">The brush used to paint the text</param> public void DrawText(string text, D2dTextFormat textFormat, RectangleF layoutRect, D2dBrush brush) { using (var layout = new SharpDX.DirectWrite.TextLayout(D2dFactory.NativeDwFactory, text, textFormat.NativeTextFormat, layoutRect.Width, layoutRect.Height)) { if (textFormat.Underlined) layout.SetUnderline(true, new SharpDX.DirectWrite.TextRange(0, text.Length)); if (textFormat.Strikeout) layout.SetStrikethrough(true, new SharpDX.DirectWrite.TextRange(0, text.Length)); m_renderTarget.DrawTextLayout( layoutRect.Location.ToSharpDX(), layout, brush.NativeBrush, (DrawTextOptions)textFormat.DrawTextOptions); } }
public override void OnRender(ChartControl chartControl, ChartScale chartScale) { if (firstTime && DrawingState == DrawingState.Normal) { firstTime = false; Cbi.License.Log("Path"); } RenderTarget.AntialiasMode = SharpDX.Direct2D1.AntialiasMode.PerPrimitive; Stroke outlineStroke = OutlineStroke; outlineStroke.RenderTarget = RenderTarget; ChartPanel chartPanel = chartControl.ChartPanels[PanelIndex]; double strokePixAdjust = outlineStroke.Width % 2 == 0 ? 0.5d : 0d; Vector pixelAdjustVec = new Vector(strokePixAdjust, strokePixAdjust); SharpDX.Direct2D1.PathGeometry polyGeo = CreatePathGeometry(chartControl, chartPanel, chartScale, strokePixAdjust); SharpDX.Direct2D1.Brush tmpBrush = IsInHitTest ? chartControl.SelectionBrush : outlineStroke.BrushDX; RenderTarget.DrawGeometry(polyGeo, tmpBrush, outlineStroke.Width, outlineStroke.StrokeStyle); polyGeo.Dispose(); if (PathBegin == PathToolCapMode.Arrow || PathEnd == PathToolCapMode.Arrow) { Point[] points = GetPathAnchorPoints(chartControl, chartScale); if (points.Length > 1) { if (arrowPathGeometry == null) { arrowPathGeometry = new SharpDX.Direct2D1.PathGeometry(Core.Globals.D2DFactory); SharpDX.Direct2D1.GeometrySink geometrySink = arrowPathGeometry.Open(); float arrowWidth = 6f; SharpDX.Vector2 top = new SharpDX.Vector2(0, outlineStroke.Width * 0.5f); geometrySink.BeginFigure(top, SharpDX.Direct2D1.FigureBegin.Filled); geometrySink.AddLine(new SharpDX.Vector2(arrowWidth, -arrowWidth)); geometrySink.AddLine(new SharpDX.Vector2(-arrowWidth, -arrowWidth)); geometrySink.AddLine(top); // cap off figure geometrySink.EndFigure(SharpDX.Direct2D1.FigureEnd.Closed); geometrySink.Close(); } if (PathBegin == PathToolCapMode.Arrow) { Vector lineVector = points[0] - points[1]; lineVector.Normalize(); Point pointAdjusted = points[0] + pixelAdjustVec; SharpDX.Vector2 pointVec = pointAdjusted.ToVector2(); float vectorAngle = -(float)Math.Atan2(lineVector.X, lineVector.Y); Vector adjustVector = lineVector * 5; SharpDX.Vector2 arrowPointVec = new SharpDX.Vector2((float)(pointVec.X + adjustVector.X), (float)(pointVec.Y + adjustVector.Y)); SharpDX.Matrix3x2 transformMatrix2 = SharpDX.Matrix3x2.Rotation(vectorAngle, SharpDX.Vector2.Zero) * SharpDX.Matrix3x2.Scaling((float)Math.Max(1.0f, outlineStroke.Width * .45) + 0.25f) * SharpDX.Matrix3x2.Translation(arrowPointVec); RenderTarget.Transform = transformMatrix2; RenderTarget.FillGeometry(arrowPathGeometry, tmpBrush); RenderTarget.Transform = SharpDX.Matrix3x2.Identity; } if (PathEnd == PathToolCapMode.Arrow) { Vector lineVector = points[points.Length - 1] - points[points.Length - 2]; lineVector.Normalize(); Point pointAdjusted = points[points.Length - 1] + pixelAdjustVec; SharpDX.Vector2 pointVec = pointAdjusted.ToVector2(); float vectorAngle = -(float)Math.Atan2(lineVector.X, lineVector.Y); Vector adjustVector = lineVector * 5; SharpDX.Vector2 arrowPointVec = new SharpDX.Vector2((float)(pointVec.X + adjustVector.X), (float)(pointVec.Y + adjustVector.Y)); SharpDX.Matrix3x2 transformMatrix2 = SharpDX.Matrix3x2.Rotation(vectorAngle, SharpDX.Vector2.Zero) * SharpDX.Matrix3x2.Scaling((float)Math.Max(1.0f, outlineStroke.Width * .45) + 0.25f) * SharpDX.Matrix3x2.Translation(arrowPointVec); RenderTarget.Transform = transformMatrix2; RenderTarget.FillGeometry(arrowPathGeometry, tmpBrush); RenderTarget.Transform = SharpDX.Matrix3x2.Identity; } } } if (ShowCount) { SimpleFont wpfFont = chartControl.Properties.LabelFont ?? new SimpleFont(); SharpDX.DirectWrite.TextFormat textFormat = wpfFont.ToDirectWriteTextFormat(); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading; textFormat.WordWrapping = SharpDX.DirectWrite.WordWrapping.NoWrap; for (int i = 1; i < ChartAnchors.Count; i++) { Point p = ChartAnchors[i - 1].GetPoint(chartControl, chartPanel, chartScale); Point p1 = ChartAnchors[i].GetPoint(chartControl, chartPanel, chartScale); if (i + 1 < ChartAnchors.Count) { Point p2 = ChartAnchors[i + 1].GetPoint(chartControl, chartPanel, chartScale); Vector v1 = p - p1; v1.Normalize(); Vector v2 = p2 - p1; v2.Normalize(); Vector vector = v1 + v2; vector.Normalize(); SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, i.ToString(), textFormat, 250, textFormat.FontSize); Point textPoint = p1 - vector * textFormat.FontSize; textPoint.X -= textLayout.Metrics.Width / 2f; textPoint.Y -= textLayout.Metrics.Height / 2f; RenderTarget.DrawTextLayout((textPoint + pixelAdjustVec).ToVector2(), textLayout, outlineStroke.BrushDX, SharpDX.Direct2D1.DrawTextOptions.NoSnap); textLayout.Dispose(); } else { SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(Core.Globals.DirectWriteFactory, i.ToString(), textFormat, 250, textFormat.FontSize); Vector vector = (p - p1); vector.Normalize(); Point textPoint = p1 - vector * textFormat.FontSize; textPoint.X -= textLayout.Metrics.Width / 2f; textPoint.Y -= textLayout.Metrics.Height / 2f; RenderTarget.DrawTextLayout((textPoint + pixelAdjustVec).ToVector2(), textLayout, outlineStroke.BrushDX, SharpDX.Direct2D1.DrawTextOptions.NoSnap); textLayout.Dispose(); } } textFormat.Dispose(); } }
private void DrawTextBox(bool Snap, string displayText, double x, double y, SharpDX.Direct2D1.Brush brush, SharpDX.Direct2D1.Brush bgBrush, Stroke stroke, float rotate) { const int padding = 4; // Text has changed, need to update cached TextLayout if (displayText != lastText) { needsLayoutUpdate = true; } lastText = displayText; // Update cachedTextLayout if (needsLayoutUpdate || cachedTextLayout == null) { SharpDX.DirectWrite.TextFormat textFormat = Font.ToDirectWriteTextFormat(); cachedTextLayout = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, displayText, textFormat, ChartPanel.X + ChartPanel.W, textFormat.FontSize); textFormat.Dispose(); needsLayoutUpdate = false; } // Snap TextBox coordinates to ChartPanel when out of bounds if (Snap) { if (rotate == 1.5708f) { y = Math.Max(ChartPanel.Y + cachedTextLayout.Metrics.Width + 2 * padding, y); } else { y = Math.Min(ChartPanel.H - padding, y); y = Math.Max(ChartPanel.Y + cachedTextLayout.Metrics.Height + padding, y); x = Math.Max(ChartPanel.X + cachedTextLayout.Metrics.Width + 2 * padding, x); } } // Apply rotation RenderTarget.Transform = SharpDX.Matrix3x2.Rotation(rotate, new SharpDX.Vector2((float)x, (float)y)); // Add padding to TextPlotPoint SharpDX.Vector2 TextPlotPoint = new System.Windows.Point(x - cachedTextLayout.Metrics.Width - padding / 2, y - cachedTextLayout.Metrics.Height).ToVector2(); // Draw the TextBox if (displayText.Length > 0) { SharpDX.RectangleF PLBoundRect = new SharpDX.RectangleF((float)x - cachedTextLayout.Metrics.Width - padding, (float)y - cachedTextLayout.Metrics.Height - padding / 2, cachedTextLayout.Metrics.Width + padding, cachedTextLayout.Metrics.Height + padding); SharpDX.Direct2D1.RoundedRectangle PLRoundedRect = new SharpDX.Direct2D1.RoundedRectangle() { Rect = PLBoundRect, RadiusX = cachedTextLayout.FontSize / 4, RadiusY = cachedTextLayout.FontSize / 4 }; RenderTarget.FillRoundedRectangle(PLRoundedRect, bgBrush); RenderTarget.DrawRoundedRectangle(PLRoundedRect, stroke.BrushDX, stroke.Width, stroke.StrokeStyle); // Draw the TextLayout RenderTarget.DrawTextLayout(TextPlotPoint, cachedTextLayout, brush, SharpDX.Direct2D1.DrawTextOptions.NoSnap); } // Restore rotation RenderTarget.Transform = SharpDX.Matrix3x2.Identity; }
/// <summary> /// Draws a text layout /// </summary> /// <param name="deviceContext">Device context</param> /// <param name="textLayout">Text layout to draw</param> /// <param name="origin">Draw origin</param> /// <param name="color">Text color</param> /// <param name="flags">Draw flags</param> public void DrawTextLayout(DeviceContext deviceContext, SharpDX.DirectWrite.TextLayout textLayout, Vector2 origin, Color4 color, TextFlags flags) { this.DrawTextLayout(deviceContext, textLayout, origin.X, origin.Y, color.ToRgba(), flags); }
/// <summary> /// Draws the specified text using the format information provided at the specified location</summary> /// <param name="text">The text string to draw</param> /// <param name="textFormat">The text format object to use</param> /// <param name="upperLeft">Upper left corner of the text</param> /// <param name="brush">The brush to use to draw the text</param> public void DrawText(string text, D2dTextFormat textFormat, PointF upperLeft, D2dBrush brush) { var rtsize = Size; using (var layout = new SharpDX.DirectWrite.TextLayout(D2dFactory.NativeDwFactory, text, textFormat.NativeTextFormat, rtsize.Width, rtsize.Height)) { layout.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading; layout.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near; if (textFormat.Underlined) layout.SetUnderline(true,new SharpDX.DirectWrite.TextRange(0, text.Length)); if (textFormat.Strikeout) layout.SetStrikethrough(true,new SharpDX.DirectWrite.TextRange(0, text.Length)); m_renderTarget.DrawTextLayout(upperLeft.ToSharpDX(), layout, brush.NativeBrush, (DrawTextOptions)textFormat.DrawTextOptions); } }
/// <summary> /// Draws a text layout /// </summary> /// <param name="deviceContext">Device context</param> /// <param name="textLayout">Text layout to draw</param> /// <param name="origin">Draw origin</param> /// <param name="color">Text color</param> /// <param name="flags">Draw flags</param> /// <param name="transform">Transfomration matrix</param> public void DrawTextLayout(DeviceContext deviceContext, SharpDX.DirectWrite.TextLayout textLayout, Vector2 origin, Matrix transform, Color4 color, TextFlags flags) { this.DrawTextLayout(deviceContext, textLayout, origin.X, origin.Y, color.ToRgba(), IntPtr.Zero, new IntPtr(&transform), flags); }
/// <summary> /// Measures the specified string when drawn with the specified System.Drawing.Font</summary> /// <param name="text">String to measure</param> /// <param name="format">D2dTextFormat that defines the font and format of the string</param> /// <param name="maxSize">The maximum x and y dimensions</param> /// <returns>This method returns a System.Drawing.SizeF structure that represents the /// size, in DIP (Device Independent Pixels) units of the string specified by the text parameter as drawn /// with the format parameter</returns> public SizeF MeasureText(string text, D2dTextFormat format, SizeF maxSize) { using (var layout = new SharpDX.DirectWrite.TextLayout(D2dFactory.NativeDwFactory, text, format.NativeTextFormat, maxSize.Width, maxSize.Height)) { var metrics = layout.Metrics; return new SizeF(metrics.WidthIncludingTrailingWhitespace, metrics.Height); } }
/// <summary> /// /// </summary> /// <param name="renderTarget"></param> /// <param name="unitList"></param> private void drawUnits(WindowRenderTarget renderTarget, List <MapUnit> unitList) { for (int i = 0; i < unitList.Count; i++) { MapUnit mapUnit = unitList[i]; SharpDX.Vector2 position = new SharpDX.Vector2(X[mapUnit.Position.X], Y[mapUnit.Position.Y]); float radius = Math.Max(X.Prop(mapUnit.Radius), 0.01f); switch (mapUnit) { case AIBaseMapUnit aiBaseMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.AIBase, position, radius); Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, X.Prop(mapUnit.Radius - 3f)); break; case AIDroneMapUnit aiDroneMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.AIDrone, position, radius); Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, X.Prop(mapUnit.Radius - 3f)); break; case AIPlatformMapUnit aiPlatformMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.AIPlatform, position, radius); Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, X.Prop(mapUnit.Radius - 2f)); break; case AIProbeMapUnit aiProbeMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.AIProbe, position, radius); Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, X.Prop(mapUnit.Radius - 2f)); break; case AIShipMapUnit aiShipMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.AIShip, position, radius); Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, X.Prop(mapUnit.Radius - 2f)); break; case AsteroidMapUnit asteroidMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Asteroid, position, radius); break; case BlackHoleMapUnit blackHoleMapUnit: for (int c = 0; c < blackHoleMapUnit.GravityWellInfos.Length; c++) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.BlueViolet, position, X.Prop(blackHoleMapUnit.GravityWellInfos[c].Radius), 1f, dashedStrokeStyle); } Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.BlackHole, position, radius); break; case BuoyMapUnit buoyMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Buoy, position, radius); break; case CloakPowerUpMapUnit cloakPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.CloakPowerUp, position, radius); break; case DoubleDamagePowerUpMapUnit doubleDamagePowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.DoubleDamagePowerUp, position, radius); break; case EnergyPowerUpMapUnit energyPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.EnergyPowerUp, position, radius); break; case ExplosionMapUnit explosionMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Explosion, position, radius); break; case GateMapUnit gateMapUnit: if (gateMapUnit.Switched) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Red, position, radius); } else { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Green, position, radius, 1f, dashedStrokeStyle); } break; case HastePowerUpMapUnit hastePowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.HastePowerUp, position, radius); break; case HullPowerUpMapUnit hullPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.HullPowerUp, position, radius); break; case IonsPowerUpMapUnit ionsPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.IonsPowerUp, position, radius); break; case MeteoroidMapUnit meteoroidMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Meteoroid, position, radius); break; case MissionTargetMapUnit missionTargetMapUnit: SolidColorBrush solidColorBrush; if (missionTargetMapUnit.Team == null || missionTargetMapUnit.Team.Name == "None") { solidColorBrush = missionTargetMapUnit.IsHit ? Brushes.SolidColorBrushes.LimeGreen : Brushes.SolidColorBrushes.Red; } else { solidColorBrush = Brushes.SolidColorBrushes.TeamColors[missionTargetMapUnit.Team.Name]; } Primitives.Circle.Draw(renderTarget, solidColorBrush, position, radius); Primitives.Circle.Draw(renderTarget, solidColorBrush, position, X.Prop(mapUnit.Radius + 3f)); if (missionTargetMapUnit.DominationRadius > 0f) { if (missionTargetMapUnit.Team == null) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.GreenYellow, position, X.Prop(missionTargetMapUnit.DominationRadius)); } else { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.TeamColors[missionTargetMapUnit.Team.Name], position, X.Prop(missionTargetMapUnit.DominationRadius), X.Prop(4f)); } if (missionTargetMapUnit.DominatingTeam != null) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.TeamColors[missionTargetMapUnit.DominatingTeam.Name], position, X.Prop(missionTargetMapUnit.DominationRadius - 10f), X.Prop(8f), dashedStrokeStyle); } } else { renderTarget.DrawText( missionTargetMapUnit.Name + " (#" + missionTargetMapUnit.SequenceNumber + ")", missionTargetTextFormat, new SharpDX.Mathematics.Interop.RawRectangleF(position.X, position.Y - X.Prop(20f), position.X + 100f, position.Y + 40f), Brushes.SolidColorBrushes.MissionTarget, DrawTextOptions.NoSnap); foreach (Flattiverse.Vector tempHint in missionTargetMapUnit.Hints) { Flattiverse.Vector hint = tempHint * 20f; renderTarget.DrawLine( new SharpDX.Mathematics.Interop.RawVector2(position.X, position.Y), new SharpDX.Mathematics.Interop.RawVector2(position.X + hint.X, position.Y + hint.Y), Brushes.SolidColorBrushes.White, 2f, dashedStrokeStyle); } } break; case MoonMapUnit moonMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Moon, position, radius); break; case NebulaMapUnit nebulaMapUnit: // TODO: Nebula color handling break; case ParticlesPowerUpMapUnit particlesPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.ParticlesPowerUp, position, radius); break; case PixelMapUnit pixelMapUnit: // Skip this for now // Unused anyway break; case PlanetMapUnit planetMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Planet, position, radius); break; // TODO: Same handling as playership needed case PlayerBaseMapUnit playerBaseMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.DarkGreen, position, radius); break; case PlayerDroneMapUnit playerDroneMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.DarkGreen, position, radius); break; case PlayerPlatformMapUnit playerPlatformMapUnit: break; case PlayerProbeMapUnit playerProbeMapUnit: break; case PlayerShipMapUnit playerShipMapUnit: float penThicknessBars = 2f; using (SharpDX.DirectWrite.TextLayout textLayout = new SharpDX.DirectWrite.TextLayout(parent.DirectWriteFactory, playerShipMapUnit.Name, missionTargetTextFormat, 100f, 20f)) { float halfWidth = textLayout.Metrics.Width / 2f; renderTarget.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2(position.X - halfWidth, position.Y + radius + Y.Prop(penThicknessBars + 2f)), textLayout, Brushes.SolidColorBrushes.TeamColors[playerShipMapUnit.TeamName], SharpDX.Direct2D1.DrawTextOptions.NoSnap); } if (playerShipMapUnit.Hull > 0f) { Primitives.Arc.Draw(renderTarget, Brushes.SolidColorBrushes.OrangeRed, position, radius - X.Prop(penThicknessBars), 270f, 360f * playerShipMapUnit.Hull, X.Prop(penThicknessBars)); } if (playerShipMapUnit.Shield > 0.01f) { Primitives.Arc.Draw(renderTarget, Brushes.SolidColorBrushes.CadetBlue, position, radius - X.Prop(penThicknessBars * 3f), 270f, 360f * playerShipMapUnit.Shield, X.Prop(penThicknessBars)); } if (playerShipMapUnit.IsOwnShip) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.LightBlue, position, radius); if (currentShip.Name == playerShipMapUnit.Name) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Red, position, X.Prop(currentShip.MaxShootRadius)); } #region Health, Energy, Shield if (playerShipMapUnit.Energy > 0f) { Primitives.Arc.Draw(renderTarget, Brushes.SolidColorBrushes.BlueViolet, position, radius - X.Prop(penThicknessBars * 2f), 270f, 360f * playerShipMapUnit.Energy, X.Prop(penThicknessBars)); } float weaponLoadPercentage = playerShipMapUnit.CurrentShots / playerShipMapUnit.MaxShots; weaponLoadPercentage = weaponLoadPercentage < 0.01f ? 0.0f : weaponLoadPercentage; if (weaponLoadPercentage > 0f) { Primitives.Arc.Draw(renderTarget, Brushes.SolidColorBrushes.LightGoldenrodYellow, position, radius + X.Prop(penThicknessBars), 270f, 360f * weaponLoadPercentage, X.Prop(penThicknessBars)); } #endregion } else { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.IndianRed, position, radius); } break; case QuadDamagePowerUpMapUnit quadDamagePowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.QuadDamagePowerUp, position, radius); break; case ShieldPowerUpMapUnit shieldPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.ShieldPowerUp, position, radius); break; case ShotMapUnit shotMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Shot, position, radius); break; case ShotProductionPowerUpMapUnit shotProductionPowerUpMapUnit: Primitives.Circle.Fill(renderTarget, Brushes.SolidColorBrushes.ShotProductionPowerUp, position, radius); break; case SpaceJellyFishMapUnit spaceJellyFishMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.SpaceJellyFish, position, radius); break; case SpaceJellyFishSlimeMapUnit spaceJellyFishSlimeMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.SpaceJellyFishSlime, position, radius, 1f, dashedStrokeStyle); break; case StormCommencingWhirlMapUnit stormCommencingWhirlMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.StormCommencingWhirl, position, radius, 1f, dashedStrokeStyle); break; case StormMapUnit stormMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Storm, position, radius); break; case StormWhirlMapUnit stormWhirlMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.StormWhirl, position, radius); break; case SunMapUnit sunMapUnit: for (int c = 0; c < sunMapUnit.CoronaInfos.Length; c++) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.LightYellow, position, X.Prop(sunMapUnit.CoronaInfos[c].Radius), 1f, dashedStrokeStyle); } Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Sun, position, radius); break; case SwitchMapUnit switchMapUnit: if (switchMapUnit.Switched) { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Red, position, radius); } else { Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Green, position, radius, 1f, dashedStrokeStyle); } break; case TotalRefreshPowerUpMapUnit totalRefreshPowerUpMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.TotalRefreshPowerUp, position, radius); break; case UnknownMapUnit unknownMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.Unknown, position, radius); break; case WormHoleMapUnit wormHoleMapUnit: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.WormHole, position, radius); break; default: Primitives.Circle.Draw(renderTarget, Brushes.SolidColorBrushes.White, position, radius); break; } } }