public void DrawEllipse( IElement element, IFrameContext context, PxPoint pt, PxPoint radius, Fill fill, Stroke strokeStyle ) { if (MathEx.IsZero(radius.X) || MathEx.IsZero(radius.Y)) { return; } var ellipse = new D2D1.Ellipse( new DXM.RawVector2(pt.X, pt.Y), radius.X, radius.Y ); var fillBrush = CreateBrush(element, context, fill.Brush, fill.Opacity); var strokeBrush = strokeStyle.Width > 0 ? CreateBrush(element, context, strokeStyle.Brush, strokeStyle.Opacity) : null; if (fillBrush != null) { Target.FillEllipse(ellipse, fillBrush); } if (strokeBrush != null) { Target.DrawEllipse(ellipse, strokeBrush, strokeStyle.Width, GetStrokeStyle(strokeStyle)); } }
public void UpdateGeometries() { float halfWidth = Size.X / 2, halfHeight = Size.Y / 2; BorderRect.Left = Center.X - halfWidth; BorderRect.Right = Center.X + halfWidth; BorderRect.Top = Center.Y - halfHeight; BorderRect.Bottom = Center.Y + halfHeight; if (BorderWidth > 0) { ContentRect.Left = BorderRect.Left + BorderWidth; ContentRect.Right = BorderRect.Right - BorderWidth; ContentRect.Top = BorderRect.Top + BorderWidth; ContentRect.Bottom = BorderRect.Bottom - BorderWidth; } else { ContentRect = BorderRect; } var radius = Math.Min(Size.X, Size.Y) / 100; CenterPointEllipse = new D2D1.Ellipse(Center, radius, radius); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Конструктор инициализирует объект класса указанными параметрами /// </summary> /// <param name="center_point">Центр эллипса</param> /// <param name="radius_x">Радиус эллипса по X</param> /// <param name="radius_y">Радиус эллипса по Y</param> //--------------------------------------------------------------------------------------------------------- public CCadDirect2DPrimitiveEllipse(Vector2Df center_point, Single radius_x, Single radius_y) { mBoundsRect.Center = center_point; mBoundsRect.Width = radius_x * 2; mBoundsRect.Height = radius_y * 2; mD2DEllipse = new Direct2D.Ellipse(center_point.ToRawVector2(), radius_x, radius_y); }
private void UpdateFixation() { var clientSize = ClientSize; var fixationSize = _paradigm.Config.Gui.FixationPoint.Size; _fixationPoint = new D2D1.Ellipse(new RawVector2(clientSize.Width / 2F, clientSize.Height / 2F), fixationSize, fixationSize); }
public D3D11Renderer(ObservableVideoTrack videoTrack, RendererOptions options) : base(videoTrack, options) { // _factoryDWrite = new DWrite.Factory(DWrite.FactoryType.Shared); var device2D = new D2D1.Device(DeviceDXGI, new D2D1.CreationProperties { DebugLevel = D2D1.DebugLevel.Warning, ThreadingMode = D2D1.ThreadingMode.MultiThreaded, Options = D2D1.DeviceContextOptions.None }); _context2D = new D2D1.DeviceContext(device2D, D2D1.DeviceContextOptions.None); // Load the background image using (var factoryWic = new WIC.ImagingFactory2()) using (var decoder = new WIC.JpegBitmapDecoder(factoryWic)) using (var inputStream = new WIC.WICStream(factoryWic, "background-small.jpg", NativeFileAccess.Read)) using (var formatConverter = new WIC.FormatConverter(factoryWic)) using (var bitmapScaler = new WIC.BitmapScaler(factoryWic)) { decoder.Initialize(inputStream, WIC.DecodeOptions.CacheOnLoad); formatConverter.Initialize(decoder.GetFrame(0), WIC.PixelFormat.Format32bppPBGRA); bitmapScaler.Initialize(formatConverter, VideoFrameWidth, VideoFrameHeight, WIC.BitmapInterpolationMode.Fant); _backgroundBitmap = D2D1.Bitmap1.FromWicBitmap(_context2D, bitmapScaler); } // Create render target _ballEllipse = new D2D1.Ellipse { RadiusX = VideoFrameWidth / 20f, RadiusY = VideoFrameWidth / 20f }; _ballBrush = new D2D1.SolidColorBrush(_context2D, new RawColor4(1f, 1f, 0f, 1f)); }
public void AddEllipse(float x, float y, float width, float height) { CloseSink(); var ellipse = new sd.Ellipse(new s.Vector2(x + width / 2, y + height / 2), width / 2, height / 2); geometries.Add(new sd.EllipseGeometry(SDFactory.D2D1Factory, ellipse)); control = null; }
public void DrawGripper(Point p, double radius) { D2D.Ellipse ellipse = new D2D.Ellipse(); ellipse.Point = p; ellipse.RadiusX = (float)radius; ellipse.RadiusY = (float)radius; this.render.FillEllipse(ellipse, this._factory.GetSolidColorBrush(this.Background)); this.render.DrawEllipse(ellipse, this._factory.GetSolidColorBrush(this.Foreground)); }
public void Draw(ServiceResult serviceResult, float currentTime, float duration) { if (!uiInitialized) { return; } if (!redraw) { return; } redraw = false; target2d.BeginDraw(); target2d.Clear(new Color4(0, 0, 0, 0.7f)); target2d.DrawLine(new Vector2(0, 1), new Vector2(1024, 1), blueBrush, 2); target2d.DrawLine(new Vector2(0, 511), new Vector2(1024, 511), blueBrush, 2); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; if (serviceResult.contentType == ServiceResult.ContentType.video) { target2d.DrawText("now playing:", textFormatSmall, new RectangleF(0, 0, 1024, 100), textBrush); target2d.DrawText(serviceResult.TitleWithFallback, textFormat, new RectangleF(0, 50, 1024, 100), textBrush); var barLength = 1024 - 265; var currentLength = barLength * (currentTime / duration); target2d.DrawLine(new Vector2(128, 384), new Vector2(1024 - 128, 384), textBrush, 6); target2d.DrawLine(new Vector2(128, 384), new Vector2(128 + currentLength, 384), blueBrush, 6); var ellipse = new DX2D.Ellipse(new Vector2(128 + currentLength + 3.5f, 384), 7, 7); target2d.FillEllipse(ellipse, blueBrush); target2d.DrawEllipse(new DX2D.Ellipse(new Vector2(512, 256), 48, 48), textBrush, 2); var dist = 8; var len = 10; target2d.DrawLine(new Vector2(512 - dist, 256 - len), new Vector2(512 - dist, 256 + len), textBrush, 2); target2d.DrawLine(new Vector2(512 + dist, 256 - len), new Vector2(512 + dist, 256 + len), textBrush, 2); textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Trailing; target2d.DrawText((new TimeSpan(0, 0, (int)Math.Floor(duration))).ToString(), textFormatSmall, new Rectangle(1024 - 128 - 150, 384, 150, 50), textBrush); int positionx = (int)(128 + currentLength - 74 / 2); positionx = MathUtil.Clamp(positionx, 128, 1024 - 128 - 74); textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; target2d.DrawText((new TimeSpan(0, 0, (int)Math.Floor(currentTime))).ToString(), textFormatSmall, new Rectangle(positionx, 340, 74, 32), textBrush); } target2d.EndDraw(); }
public Clock(Size clientSize) { ClientSize = clientSize; g_center = new PointF(ClientSize.Width / 2f, ClientSize.Height / 2f); // Create brushes blueBrush1 = new D2D.SolidColorBrush(RenderForm.RenderTarget, new Mathe.RawColor4(0.3f, 0.4f, 0.9f, 1)); blueBrush2 = new D2D.SolidColorBrush(RenderForm.RenderTarget, new Mathe.RawColor4(0.45f, 0.6f, 0.95f, 1)); blueBrush3 = new D2D.SolidColorBrush(RenderForm.RenderTarget, new Mathe.RawColor4(0.6f, 0.8f, 1f, 1)); whiteBrush = new D2D.SolidColorBrush(RenderForm.RenderTarget, new Mathe.RawColor4(1f, 1f, 1f, 0.5f)); redBrush = new D2D.SolidColorBrush(RenderForm.RenderTarget, new Mathe.RawColor4(0.99f, 0.16f, 0.3f, 0.7f)); // Create ellipses ellipseCentre = new D2D.Ellipse(new Mathe.RawVector2(g_center.X, g_center.Y), 120, 120); // Create text formats textFormat = new DW.TextFormat(RenderForm.FactoryWrite, "Berlin Sans FB", 36); strokeProperties = new D2D.StrokeStyleProperties { StartCap = D2D.CapStyle.Round, EndCap = D2D.CapStyle.Triangle }; strokeStyle = new D2D.StrokeStyle(RenderForm.Factory, strokeProperties); strokeProperties2 = new D2D.StrokeStyleProperties { StartCap = D2D.CapStyle.Round, EndCap = D2D.CapStyle.Round, DashStyle = D2D.DashStyle.Dash }; strokeStyle2 = new D2D.StrokeStyle(RenderForm.Factory, strokeProperties2); int len = 110; for (int i = 0; i < 60; i++) { int r = i % 5 == 0 ? 10 : 5; float deg, rad; deg = (i / 60f * 360 - 90); rad = deg / 180 * (float)Math.PI; lim[i] = new PointF(g_center.X + (float)Math.Cos(rad) * (len - r), g_center.Y + (float)Math.Sin(rad) * (len - r)); lim2[i] = new PointF(g_center.X + (float)Math.Cos(rad) * (len), g_center.Y + (float)Math.Sin(rad) * (len)); } sw = new Stopwatch(); sw.Start(); }
public Circle( IVertex<float> Center, float Radius ) { // set the local radius m_Center = Center; m_Radius = Radius; // allocate the ellipse for the render m_Ellipse = new Ellipse(); // init the ellipse m_Ellipse.Point = new SharpDX.Vector2( m_Center.X, m_Center.Y ); m_Ellipse.RadiusX = Radius; m_Ellipse.RadiusY = Radius; }
protected override void InitializeDirectXResources() { base.InitializeDirectXResources(); _textFormat = new DW.TextFormat(DwFactory, "Arial", DW.FontWeight.Bold, DW.FontStyle.Normal, DW.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale) { TextAlignment = DW.TextAlignment.Center, ParagraphAlignment = DW.ParagraphAlignment.Center }; var clientSize = ClientSize; var fixationSize = _experiment.Config.Gui.FixationPoint.Size; _fixationPoint = new D2D1.Ellipse(new RawVector2(clientSize.Width / 2F, clientSize.Height / 2F), fixationSize, fixationSize); }
private void GenerateStimuli() { var xSign = Math.Sign(_stimPos); var stimulusSize = (float)_experiment.Config.Gui.Stimulus.Size; var tolerance = (float)_experiment.Config.Gui.Stimulus.Tolerance; for (var i = 0; i < _stimulusPoints.Length; i++) { _stimulusPoints[i] = new D2D1.Ellipse(new RawVector2 { X = _fixationPoint.Point.X + xSign * (float)_experiment.Config.Gui.Stimulus.HorizontalOffset + _session.R.NextFloat(-tolerance, +tolerance), Y = _fixationPoint.Point.Y + (float)_experiment.Config.Gui.Stimulus.VerticalOffset + _session.R.NextFloat(-tolerance, +tolerance) }, stimulusSize, stimulusSize); } }
public void UpdateGeometries(RawVector2 center, RawVector2 size) { Center = center; Size = size; BorderRect = SharpDXUtils.CenteredRect(center, size); ContentRect = BorderWidth > 0 ? BorderRect.Shrink(BorderWidth) : BorderRect; var absoluteMargins = FlickerMargins.GetAbsolute(ContentRect.Width(), ContentRect.Height()); FlickerRect = absoluteMargins.IsEmpty(0.1) ? ContentRect : ContentRect.Shrink((float)absoluteMargins.Left, (float)absoluteMargins.Top, (float)absoluteMargins.Right, (float)absoluteMargins.Bottom); FixationPoint = new D2D1.Ellipse(FlickerRect.Center(), FixationPointSize, FixationPointSize); }
public void DrawEllipse(Rect frame, Pen pen = null, Brush brush = null) { var p = GetBrush(pen); var b = GetBrush(frame, brush); var c = frame.Center; var s = new D2D1.Ellipse(new Vector2((float)c.X, (float)c.Y), (float)(frame.Width / 2.0), (float)(frame.Height / 2.0)); if (b != null) { renderTarget.FillEllipse(s, b); } if (p != null) { renderTarget.DrawEllipse(s, p, (float)pen.Width, GetStrokeStyle(pen)); } }
internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Ellipse ellipse) { var rect = ellipse.GetBoundingRect(rootElement).ToSharpDX(); var d2dEllipse = new D2D.Ellipse( new Vector2( (float)((rect.Left + rect.Right) * 0.5), (float)((rect.Top + rect.Bottom) * 0.5)), (float)(0.5 * rect.Width), (float)(0.5 * rect.Height)); var fill = await ellipse.Fill.ToSharpDX(renderTarget, rect); var layer = ellipse.CreateAndPushLayerIfNecessary(renderTarget, rootElement); var stroke = await ellipse.Stroke.ToSharpDX(renderTarget, rect); if (ellipse.StrokeThickness > 0 && stroke != null) { var halfStrokeThickness = (float)(ellipse.StrokeThickness * 0.5); d2dEllipse.RadiusX -= halfStrokeThickness; d2dEllipse.RadiusY -= halfStrokeThickness; if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } renderTarget.DrawEllipse( d2dEllipse, stroke, (float)ellipse.StrokeThickness, ellipse.GetStrokeStyle(compositionEngine.D2DFactory)); } else if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } if (layer != null) { renderTarget.PopLayer(); layer.Dispose(); } }
internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Ellipse ellipse) { var rect = ellipse.GetBoundingRect(rootElement).ToSharpDX(); var d2dEllipse = new D2D.Ellipse( new DrawingPointF( (float)((rect.Left + rect.Right) * 0.5), (float)((rect.Top + rect.Bottom) * 0.5)), (float)(0.5 * rect.Width), (float)(0.5 * rect.Height)); var fill = await ellipse.Fill.ToSharpDX(renderTarget, rect); //var layer = new Layer(renderTarget); //var layerParameters = new LayerParameters(); //layerParameters.ContentBounds = rect; //renderTarget.PushLayer(ref layerParameters, layer); var stroke = await ellipse.Stroke.ToSharpDX(renderTarget, rect); if (ellipse.StrokeThickness > 0 && stroke != null) { var halfStrokeThickness = (float)(ellipse.StrokeThickness * 0.5); d2dEllipse.RadiusX -= halfStrokeThickness; d2dEllipse.RadiusY -= halfStrokeThickness; if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } renderTarget.DrawEllipse( d2dEllipse, stroke, (float)ellipse.StrokeThickness, ellipse.GetStrokeStyle(compositionEngine.D2DFactory)); } else if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } //renderTarget.PopLayer(); }
internal static void Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Ellipse ellipse) { var rect = ellipse.GetBoundingRect(rootElement).ToSharpDX(); var d2dEllipse = new D2D.Ellipse( new DrawingPointF( (float)((rect.Left + rect.Right) * 0.5), (float)((rect.Top + rect.Bottom) * 0.5)), (float)(0.5 * rect.Width), (float)(0.5 * rect.Height)); var fill = ellipse.Fill.ToSharpDX(renderTarget, rect); //var layer = new Layer(renderTarget); //var layerParameters = new LayerParameters(); //layerParameters.ContentBounds = rect; //renderTarget.PushLayer(ref layerParameters, layer); var stroke = ellipse.Stroke.ToSharpDX(renderTarget, rect); if (ellipse.StrokeThickness > 0 && stroke != null) { var halfStrokeThickness = (float)(ellipse.StrokeThickness * 0.5); d2dEllipse.RadiusX -= halfStrokeThickness; d2dEllipse.RadiusY -= halfStrokeThickness; if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } renderTarget.DrawEllipse( d2dEllipse, stroke, (float)ellipse.StrokeThickness, ellipse.GetStrokeStyle(compositionEngine.D2DFactory)); } else if (fill != null) { renderTarget.FillEllipse(d2dEllipse, fill); } //renderTarget.PopLayer(); }
/// <summary> /// Draw an ellipse in a rectangle. /// </summary> /// <param name="rectangle"></param> /// <param name="color"></param> public void Draw(int layerIndex, System.Drawing.RectangleF rectangle, System.Drawing.Bitmap bitmap, System.Drawing.Color?borderColor, float opacity = 1) { if (bitmap != prevBitmap) { prevBitmap = bitmap; bitmapBrush = new BitmapBrush(device.renderTarget, Convertor.ConvertDrawingBmpToDirectxBmp(device.renderTarget, prevBitmap)); bitmapBrush.InterpolationMode = BitmapInterpolationMode.Linear; bitmapBrush.Opacity = opacity; bitmapBrush.ExtendModeX = ExtendMode.Wrap; bitmapBrush.ExtendModeY = ExtendMode.Wrap; } var tmpEllipse = new SharpDX.Direct2D1.Ellipse(new Vector2(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2), rectangle.Width / 2, rectangle.Height / 2); device.layers[layerIndex].FillEllipse(tmpEllipse, bitmapBrush); if (borderColor != null) { device.layers[layerIndex].DrawEllipse(tmpEllipse, new SharpDX.Direct2D1.SolidColorBrush(device.renderTarget, xPFT.DrawingBase.Convertor.ColorConvertor((System.Drawing.Color)borderColor, opacity)), lineWidth); } }
public static void DrawPoint(D2D1.RenderTarget renderTarget, D2D1.Factory factory, IPoint point, D2D1.Brush b, float size, Vector2 offset, Map map) { if (point == null) { return; } var pp = TransformToImage(point.Coordinate, map); if (double.IsNaN(point.X)) { return; } pp += offset; var e = new D2D1.Ellipse(pp, size, size); renderTarget.FillEllipse(e, b); renderTarget.DrawEllipse(e, b); }
/// <summary> /// Draw an ellipse in a rectangle. /// </summary> /// <param name="rectangle"></param> /// <param name="color"></param> public void Draw(int layerIndex, System.Drawing.RectangleF rectangle, System.Drawing.Color?borderColor, System.Drawing.Color?fillColor, float opacity, xPFT.Charting.Base.FillPattern fillPattern, float patternSize) { var tmpEllipse = new SharpDX.Direct2D1.Ellipse(new Vector2(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2), rectangle.Width / 2, rectangle.Height / 2); if (fillColor != null) { if (device.renderTarget != prevRenderTarget || fillColor != prevFillColor || fillPattern != prevFillPattern || opacity != prevOpacity) { fillBrush = BrushMaker.GetPatternBrush(device.renderTarget, (System.Drawing.Color)fillColor, opacity, fillPattern, patternSize); prevFillColor = (System.Drawing.Color)fillColor; prevFillPattern = fillPattern; prevOpacity = opacity; prevRenderTarget = device.renderTarget; } device.layers[layerIndex].FillEllipse(tmpEllipse, fillBrush); } if (borderColor != null) { device.layers[layerIndex].DrawEllipse(tmpEllipse, new SharpDX.Direct2D1.SolidColorBrush(device.renderTarget, xPFT.DrawingBase.Convertor.ColorConvertor((System.Drawing.Color)borderColor, opacity)), lineWidth); } }
/// <summary> /// 使用 SharpDX 繪製橢圓形(有填滿顏色) /// </summary> /// <param name="p1x">中心點 X 座標值</param> /// <param name="p1y">中心點 Y 座標值</param> /// <param name="p2x">橢圓的水平尺寸</param> /// <param name="p2y">橢圓的垂直尺寸</param> /// <param name="brush">XMAL中用到的顏色列舉值</param> public void DrawFillEllipse(float p1x, float p1y, float p2x, float p2y, SolidColorBrush brush) { Ellipse Ellipse = new SharpDX.Direct2D1.Ellipse(new Vector2(p1x, p1y), p2x, p2y); d2dContext.FillEllipse(Ellipse, brush); }
/// <summary> /// Loads scene-specific content. /// </summary> private void LoadContent() { // reusable structure representing a text font with size and style _textFormat = _disposeCollector.Collect(new DW.TextFormat(_dwFactory, "Segoe UI", SharpDX.DirectWrite.FontWeight.SemiBold, SharpDX.DirectWrite.FontStyle.Italic, 16f)); // reusable brush structure _textBrush = _disposeCollector.Collect(new D2D.SolidColorBrush(_d2dDeviceContext, Color.Black)); // prebaked text - useful for constant labels as it greatly improves performance _textLayout = _disposeCollector.Collect(new DW.TextLayout(_dwFactory, "Demo DirectWrite text here.", _textFormat, 100f, 100f)); // another brush for ellipse outline _ellipseStrokeBrush = _disposeCollector.Collect(new D2D.SolidColorBrush(_d2dDeviceContext, Color.Blue)); // this is a structure so it is ok to recreate it every frame, but better to create only once, if possible _ellipse = new D2D.Ellipse(new Vector2(320, 240), 150, 100); // reusable structure describing a radial gradient properties var gradientProperties = new D2D.RadialGradientBrushProperties { Center = _ellipse.Point, RadiusX = _ellipse.RadiusX, RadiusY = _ellipse.RadiusY }; // gradient color description - here we'll draw a rainbow var gradientStops = _disposeCollector.Collect(new D2D.GradientStopCollection(_d2dDeviceContext, new[] { new D2D.GradientStop {Position = 0.00f, Color = Color.Red}, new D2D.GradientStop {Position = 0.16f, Color = Color.Orange}, new D2D.GradientStop {Position = 0.33f, Color = Color.Yellow}, new D2D.GradientStop {Position = 0.50f, Color = Color.Green}, new D2D.GradientStop {Position = 0.66f, Color = Color.LightBlue}, new D2D.GradientStop {Position = 0.83f, Color = Color.Blue}, new D2D.GradientStop {Position = 1.00f, Color = Color.Violet} })); // a radial gradient brush _ellipseFillBrush = _disposeCollector.Collect(new D2D.RadialGradientBrush(_d2dDeviceContext, ref gradientProperties, gradientStops)); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Обновление данных эллипса /// </summary> //--------------------------------------------------------------------------------------------------------- public override void Update() { mD2DEllipse = new Direct2D.Ellipse(mBoundsRect.Center.ToRawVector2(), mBoundsRect.Width / 2, mBoundsRect.Height / 2); }
/// <summary> /// Draws the outline of the specified ellipse using the specified stroke style. /// </summary> /// <remarks> /// The {{DrawEllipse}} method doesn't return an error code if it fails. To determine whether a drawing operation (such as DrawEllipse) failed, check the result returned by the <see cref="M:SharpDX.Direct2D1.RenderTarget.EndDraw(System.Int64@,System.Int64@)" /> or <see cref="M:SharpDX.Direct2D1.RenderTarget.Flush(System.Int64@,System.Int64@)" /> methods. /// </remarks> /// <param name="ellipse">The position and radius of the ellipse to draw, in device-independent pixels. </param> /// <param name="brush">The brush used to paint the ellipse's outline. </param> /// <unmanaged>void ID2D1RenderTarget::DrawEllipse([In] const D2D1_ELLIPSE* ellipse,[In] ID2D1Brush* brush,[None] float strokeWidth,[In, Optional] ID2D1StrokeStyle* strokeStyle)</unmanaged> public void DrawEllipse(Ellipse ellipse, Brush brush) { DrawEllipse(ellipse, brush, StrokeWidth, null); }
public void Ellipse(Rectangle rectangle) { if (Filling) { var r = fillRect(rectangle); var ellipse = new Ellipse(Import.Point(r.Left + r.Width/2, r.Top + r.Height/2), r.Width/2, r.Height/2); _target.FillEllipse(ellipse, _fillBrush.Brush); } if (Stroking) { var r = strokeAlignedRect(rectangle); var ellipse = new Ellipse(Import.Point(r.Left + r.Width / 2, r.Top + r.Height / 2), r.Width / 2, r.Height / 2); _target.DrawEllipse(ellipse, _strokeBrush.Brush, StrokeWeight); } }
private async Task <RenderDTO> AddUpdateUIElementState_Rectangle(UIElementState uistate, RenderDTO rDto) { if (rDto == null) { ShapeDTO dto = new ShapeDTO(); dto.AggregateId = uistate.AggregateId; rDto = new RenderDTO() { ShapeDTO = dto, Type = eRenderType.Shape, Order = _renderTree.Count() + 1 }; _renderTree.Add(rDto); } switch (uistate.udfString1) { case "Rectangle": RectangleF newGeometry1 = new RectangleF(0, 0, (float)uistate.Width, (float)uistate.Height); rDto.ShapeDTO.Shape = new SharpDX.Direct2D1.RectangleGeometry(_deviceManager.FactoryDirect2D, newGeometry1); rDto.ShapeDTO.Type = uistate.udfInt1; break; case "Ellipse": SharpDX.Direct2D1.Ellipse newGeometry2 = new SharpDX.Direct2D1.Ellipse( new Vector2(((float)uistate.Width / 2), ((float)uistate.Height / 2)), (float)uistate.Width, (float)uistate.Height ); rDto.ShapeDTO.Shape = new SharpDX.Direct2D1.EllipseGeometry(_deviceManager.FactoryDirect2D, newGeometry2); rDto.ShapeDTO.Type = uistate.udfInt1; break; } //stroke stuff rDto.ShapeDTO.StrokeWidth = (float)uistate.udfDouble3; if (!string.IsNullOrEmpty(uistate.udfString4)) { var strokeParts = uistate.udfString4.Split("|".ToCharArray()); if (strokeParts.Length > 0) { rDto.ShapeDTO.DashOffset = float.Parse(strokeParts[0]); rDto.ShapeDTO.MiterLimit = float.Parse(strokeParts[1]); rDto.ShapeDTO.DashStyleIndex = int.Parse(string.IsNullOrEmpty(strokeParts[2]) ? "0" : strokeParts[2]); if (rDto.ShapeDTO.DashStyleIndex < 0) { rDto.ShapeDTO.DashStyleIndex = 0; } if (rDto.ShapeDTO.DashStyleIndex == 5) { rDto.ShapeDTO.DashStyleIndex = 0; } } } if (uistate.udfInt2 == 1) { var parts1 = uistate.udfString2.Split("|".ToCharArray()); var parts2 = uistate.udfString3.Split("|".ToCharArray()); Color4 colorToUse1; Color4 colorToUse2; try { colorToUse1 = new Color4( float.Parse(parts1[0]) / 255, float.Parse(parts1[1]) / 255, float.Parse(parts1[2]) / 255, parts1.Length > 6 ? float.Parse(parts1[6]) / 255 : float.Parse(parts1[3]) / 255 ); colorToUse2 = new Color4( float.Parse(parts2[0]) / 255, float.Parse(parts2[1]) / 255, float.Parse(parts2[2]) / 255, parts2.Length > 6 ? float.Parse(parts2[6]) / 255 : float.Parse(parts2[3]) / 255 ); } catch { colorToUse1 = Color.Black; colorToUse2 = Color.White; } rDto.ShapeDTO.Brush = CreateRadialGradientBrush(_deviceManager.ContextDirect2D, (float)uistate.Width, (float)uistate.Height, colorToUse1, colorToUse2, (float)uistate.udfDouble1 / 100, (float)uistate.udfDouble2 / 100); } else { var parts = uistate.udfString2.Split("|".ToCharArray()); Color4 colorToUse; try { colorToUse = new Color4( float.Parse(parts[0]) / 255, float.Parse(parts[1]) / 255, float.Parse(parts[2]) / 255, parts.Length > 6 ? float.Parse(parts[6]) / 255 : float.Parse(parts[3]) / 255 ); } catch { colorToUse = Color.Black; } rDto.ShapeDTO.Brush = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, colorToUse); } rDto.ShapeDTO.IsRenderable = uistate.IsRenderable; //true rDto.ShapeDTO.MainScale = new Vector3((float)uistate.Scale, (float)uistate.Scale, 1); rDto.ShapeDTO.MainTranslation = new Vector3((float)uistate.Left, (float)uistate.Top, 0); //ROTATION if (!string.IsNullOrEmpty(uistate.udfString5)) { var strokeParts = uistate.udfString5.Split("|".ToCharArray()); if (strokeParts.Length > 0) { rDto.ShapeDTO.MainRotation = new Vector3( MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[0]) ? "0" : strokeParts[0])), MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[1]) ? "0" : strokeParts[1])), MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[2]) ? "0" : strokeParts[2])) ); } } if (NumberFramesToRender < 1) { NumberFramesToRender = 1; } //TurnOnRenderingBecauseThereAreRenderableEffects(); return(rDto); }
/// <summary> /// Paints the interior of the specified ellipse</summary> /// <param name="ellipse">The position and radius, in pixels, of the ellipse to paint</param> /// <param name="brush">The brush used to paint the interior of the ellipse</param> public void FillEllipse(D2dEllipse ellipse, D2dBrush brush) { var tmpEllipse = new Ellipse(); tmpEllipse.Point = new DrawingPointF(ellipse.Center.X, ellipse.Center.Y); tmpEllipse.RadiusX = ellipse.RadiusX; tmpEllipse.RadiusY = ellipse.RadiusY; m_renderTarget.FillEllipse(tmpEllipse, brush.NativeBrush); }
// 繪圖主要方法 public virtual void Render(TargetBase target) { var context2D = target.DeviceManager.ContextDirect2D; context2D.BeginDraw(); context2D.Clear(Color.White); var sizeX = (float)target.RenderTargetBounds.Width; var sizeY = (float)target.RenderTargetBounds.Height; try { if (MainPage.pointers != null) { for (int j = 0; j < MainPage.pointers.Count; j++) { // Different color for touch points lineColorBrush = new SolidColorBrush(context2D, MainPage.pointers[j].color); for (int i = 0; i < MainPage.pointers[j].Pointers.Count; i++) { if (i == MainPage.pointers[j].Pointers.Count - 1) { float x = (float)MainPage.pointers[j].Pointers[i].X; float y = (float)MainPage.pointers[j].Pointers[i].Y; // Pointers info context2D.DrawText(string.Format("PointerID:{0}\nX:{1}\nY:{2}\n{3}", MainPage.pointers[j].PointerId, x, y, MainPage.pointers[j].DeviceType.ToString()) , textFormat, new RectangleF(x - 150, y - 100, x - 20, y - 20), sceneColorBrush); // Draw horizontal line context2D.DrawLine(new DrawingPointF(0, y), new DrawingPointF(context2D.PixelSize.Width, y), lineColorBrush); // Draw vertical line context2D.DrawLine(new DrawingPointF(x, 0), new DrawingPointF(x, context2D.PixelSize.Height), lineColorBrush); // Draw a circle (and like a Crosshair :D ) ellipse = new Ellipse(new DrawingPointF(x, y), 30, 30); context2D.DrawEllipse(ellipse, lineColorBrush); continue; } var beginPoint = new DrawingPointF((float)MainPage.pointers[j].Pointers[i].X, (float)MainPage.pointers[j].Pointers[i].Y); var endPoint = new DrawingPointF((float)MainPage.pointers[j].Pointers[i + 1].X, (float)MainPage.pointers[j].Pointers[i + 1].Y); context2D.DrawLine(beginPoint, endPoint, lineColorBrush, 10, strokeStyle); } } // Update pointers contacts context2D.DrawText(string.Format("Pointers Count:{0}/{1}", MainPage.pointers.Count, TouchCapabilities.Contacts), textFormat2, new RectangleF(8, 30, 8 + 200, 30 + 16), sceneColorBrush); } } catch (Exception ex) { Debug.WriteLine("Error:" + ex); } context2D.EndDraw(); }
/// <summary> /// Draws the outline of the specified ellipse using the specified stroke style</summary> /// <param name="ellipse">Position and radius of the ellipse to draw in pixels</param> /// <param name="brush">The brush used to paint the ellipse's outline</param> /// <param name="strokeWidth">The thickness of the ellipse's stroke. The stroke is centered on the ellipse's outline.</param> /// <param name="strokeStyle">The style of stroke to apply to the ellipse's outline or null to draw a solid line</param> public void DrawEllipse(D2dEllipse ellipse, D2dBrush brush, float strokeWidth = 1.0f, D2dStrokeStyle strokeStyle = null) { var tmpEllipse = new Ellipse(); tmpEllipse.Point = new DrawingPointF(ellipse.Center.X, ellipse.Center.Y); tmpEllipse.RadiusX = ellipse.RadiusX; tmpEllipse.RadiusY = ellipse.RadiusY; m_renderTarget.DrawEllipse(tmpEllipse, brush.NativeBrush, strokeWidth, strokeStyle != null ? strokeStyle.NativeStrokeStyle : null); }
public static void DrawPoint(D2D1.RenderTarget renderTarget, D2D1.Factory factory, IPoint point, D2D1.Brush b, float size, Vector2 offset, Map map) { if (point == null) return; var pp = TransformToImage(point.Coordinate, map); if (double.IsNaN(point.X)) return; pp += offset; var e = new D2D1.Ellipse(pp, size, size); renderTarget.FillEllipse(e, b); renderTarget.DrawEllipse(e, b); }
public void DrawEllipse(Direct2D.Ellipse ellipse, Vector2 where, int strokeWidth = 1) { D2DTarget.FillEllipse(ellipse, SolidBrush); D2DTarget.DrawEllipse(ellipse, StrokeBrush, strokeWidth); }
/// <summary> /// Converts a Rectangle into a Ellipse. /// </summary> /// <param name="ellipse">The Ellipse.</param> /// <returns>Ellipse</returns> public static Ellipse ConvertEllipse(Math.Ellipse ellipse) { var ellipseDx = new Ellipse { Point = ConvertVector(ellipse.Position), RadiusX = ellipse.RadiusX, RadiusY = ellipse.RadiusY }; return ellipseDx; }
private async Task<RenderDTO> AddUpdateUIElementState_Rectangle(UIElementState uistate, RenderDTO rDto) { if (rDto == null) { ShapeDTO dto = new ShapeDTO(); dto.AggregateId = uistate.AggregateId; rDto = new RenderDTO() { ShapeDTO = dto, Type = eRenderType.Shape, Order = _renderTree.Count() + 1 }; _renderTree.Add(rDto); } switch (uistate.udfString1) { case "Rectangle": RectangleF newGeometry1 = new RectangleF(0, 0, (float)uistate.Width, (float)uistate.Height); rDto.ShapeDTO.Shape = new SharpDX.Direct2D1.RectangleGeometry(_deviceManager.FactoryDirect2D, newGeometry1); rDto.ShapeDTO.Type = uistate.udfInt1; break; case "Ellipse": SharpDX.Direct2D1.Ellipse newGeometry2 = new SharpDX.Direct2D1.Ellipse( new Vector2(((float)uistate.Width / 2), ((float)uistate.Height / 2)), (float)uistate.Width, (float)uistate.Height ); rDto.ShapeDTO.Shape = new SharpDX.Direct2D1.EllipseGeometry(_deviceManager.FactoryDirect2D, newGeometry2); rDto.ShapeDTO.Type = uistate.udfInt1; break; } //stroke stuff rDto.ShapeDTO.StrokeWidth = (float)uistate.udfDouble3; if (!string.IsNullOrEmpty(uistate.udfString4)) { var strokeParts = uistate.udfString4.Split("|".ToCharArray()); if (strokeParts.Length > 0) { rDto.ShapeDTO.DashOffset = float.Parse(strokeParts[0]); rDto.ShapeDTO.MiterLimit = float.Parse(strokeParts[1]); rDto.ShapeDTO.DashStyleIndex = int.Parse(string.IsNullOrEmpty(strokeParts[2]) ? "0" : strokeParts[2]); if (rDto.ShapeDTO.DashStyleIndex < 0) rDto.ShapeDTO.DashStyleIndex = 0; if (rDto.ShapeDTO.DashStyleIndex == 5) rDto.ShapeDTO.DashStyleIndex = 0; } } if (uistate.udfInt2 == 1) { var parts1 = uistate.udfString2.Split("|".ToCharArray()); var parts2 = uistate.udfString3.Split("|".ToCharArray()); Color4 colorToUse1; Color4 colorToUse2; try { colorToUse1 = new Color4( float.Parse(parts1[0]) / 255, float.Parse(parts1[1]) / 255, float.Parse(parts1[2]) / 255, parts1.Length > 6 ? float.Parse(parts1[6]) / 255 : float.Parse(parts1[3]) / 255 ); colorToUse2 = new Color4( float.Parse(parts2[0]) / 255, float.Parse(parts2[1]) / 255, float.Parse(parts2[2]) / 255, parts2.Length > 6 ? float.Parse(parts2[6]) / 255 : float.Parse(parts2[3]) / 255 ); } catch { colorToUse1 = Color.Black; colorToUse2 = Color.White; } rDto.ShapeDTO.Brush = CreateRadialGradientBrush(_deviceManager.ContextDirect2D, (float)uistate.Width, (float)uistate.Height, colorToUse1, colorToUse2, (float)uistate.udfDouble1 / 100, (float)uistate.udfDouble2 / 100); } else { var parts = uistate.udfString2.Split("|".ToCharArray()); Color4 colorToUse; try { colorToUse = new Color4( float.Parse(parts[0]) / 255, float.Parse(parts[1]) / 255, float.Parse(parts[2]) / 255, parts.Length > 6 ? float.Parse(parts[6]) / 255 : float.Parse(parts[3]) / 255 ); } catch { colorToUse = Color.Black; } rDto.ShapeDTO.Brush = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, colorToUse); } rDto.ShapeDTO.IsRenderable = uistate.IsRenderable; //true rDto.ShapeDTO.MainScale = new Vector3((float)uistate.Scale, (float)uistate.Scale, 1); rDto.ShapeDTO.MainTranslation = new Vector3((float)uistate.Left, (float)uistate.Top, 0); //ROTATION if (!string.IsNullOrEmpty(uistate.udfString5)) { var strokeParts = uistate.udfString5.Split("|".ToCharArray()); if (strokeParts.Length > 0) { rDto.ShapeDTO.MainRotation = new Vector3( MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[0]) ? "0" : strokeParts[0])), MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[1]) ? "0" : strokeParts[1])), MathUtil.DegreesToRadians(float.Parse(string.IsNullOrEmpty(strokeParts[2]) ? "0" : strokeParts[2])) ); } } if (NumberFramesToRender < 1) NumberFramesToRender = 1; //TurnOnRenderingBecauseThereAreRenderableEffects(); return rDto; }
public void DrawEllipse(Rect frame, Pen pen = null, Brush brush = null) { var p = GetBrush (pen); var b = GetBrush (frame, brush); var c = frame.Center; var s = new D2D1.Ellipse (new Vector2 ((float)c.X, (float)c.Y), (float)(frame.Width / 2.0), (float)(frame.Height / 2.0)); if (b != null) { renderTarget.FillEllipse (s, b); } if (p != null) { renderTarget.DrawEllipse (s, p, (float)pen.Width, GetStrokeStyle (pen)); } }
/// <summary> /// Draws the outline of the specified ellipse</summary> /// <param name="rect">The rectangle, in pixels, that encloses the ellipse to paint</param> /// <param name="brush">The brush used to paint the ellipse's outline</param> /// <param name="strokeWidth">The thickness of the ellipse's stroke. The stroke is centered on the ellipse's outline.</param> /// <param name="strokeStyle">The style of stroke to apply to the ellipse's outline or null to draw a solid line</param> public void DrawEllipse(RectangleF rect, D2dBrush brush, float strokeWidth = 1.0f, D2dStrokeStyle strokeStyle = null) { var tmpEllipse = new Ellipse(); tmpEllipse.RadiusX = rect.Width * 0.5f; tmpEllipse.RadiusY = rect.Height * 0.5f; tmpEllipse.Point = new Vector2(rect.X + tmpEllipse.RadiusX, rect.Y + tmpEllipse.RadiusY); m_renderTarget.DrawEllipse(tmpEllipse, brush.NativeBrush, strokeWidth, strokeStyle != null ? strokeStyle.NativeStrokeStyle : null); }
/// <summary> /// Creates an <see cref="SharpDX.Direct2D1.EllipseGeometry"/>. /// </summary> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="ellipse">A value that describes the center point, x-radius, and y-radius of the ellipse geometry.</param> public EllipseGeometry(Factory factory, Ellipse ellipse) : base(IntPtr.Zero) { factory.CreateEllipseGeometry(ellipse, this); }
protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { // This sample should be used along side the help guide educational resource on this topic: // http://www.ninjatrader.com/support/helpGuides/nt8/en-us/?using_sharpdx_for_custom_chart_rendering.htm // Default plotting in base class. Uncomment if indicators holds at least one plot // in this case we would expect NOT to see the SMA plot we have as well in this sample script //base.OnRender(chartControl, chartScale); // 1.1 - SharpDX Vectors and Charting RenderTarget Coordinates // The SharpDX SDK uses "Vector2" objects to describe a two-dimensional point of a device (X and Y coordinates) SharpDX.Vector2 startPoint; SharpDX.Vector2 endPoint; // For our custom script, we need a way to determine the Chart's RenderTarget coordinates to draw our custom shapes // This info can be found within the NinjaTrader.Gui.ChartPanel class. // You can also use various chartScale and chartControl members to calculate values relative to time and price // However, those concepts will not be discussed or used in this sample // Notes: RenderTarget is always the full ChartPanel, so we need to be mindful which sub-ChartPanel we're dealing with // Always use ChartPanel X, Y, W, H - as chartScale and chartControl properties WPF units, so they can be drastically different depending on DPI set startPoint = new SharpDX.Vector2(ChartPanel.X, ChartPanel.Y); endPoint = new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, ChartPanel.Y + ChartPanel.H); // These Vector2 objects are equivalent with WPF System.Windows.Point and can be used interchangeably depending on your requirements // For convenience, NinjaTrader provides a "ToVector2()" extension method to convert from WPF Points to SharpDX.Vector2 SharpDX.Vector2 startPoint1 = new System.Windows.Point(ChartPanel.X, ChartPanel.Y + ChartPanel.H).ToVector2(); SharpDX.Vector2 endPoint1 = new System.Windows.Point(ChartPanel.X + ChartPanel.W, ChartPanel.Y).ToVector2(); // SharpDX.Vector2 objects contain X/Y properties which are helpful to recalculate new properties based on the initial vector float width = endPoint.X - startPoint.X; float height = endPoint.Y - startPoint.Y; // Or you can recalculate a new vector from existing vector objects SharpDX.Vector2 center = (startPoint + endPoint) / 2; // Tip: This check is simply added to prevent the Indicator dialog menu from opening as a user clicks on the chart // The default behavior is to open the Indicator dialog menu if a user double clicks on the indicator // (i.e, the indicator falls within the RenderTarget "hit testing") // You can remove this check if you want the default behavior implemented if (!IsInHitTest) { // 1.2 - SharpDX Brush Resources // RenderTarget commands must use a special brush resource defined in the SharpDX.Direct2D1 namespace // These resources exist just like you will find in the WPF/Windows.System.Media namespace // such as SolidColorBrushes, LienarGraidentBrushes, RadialGradientBrushes, etc. // To begin, we will start with the most basic "Brush" type // Warning: Brush objects must be disposed of after they have been used SharpDX.Direct2D1.Brush areaBrushDx; SharpDX.Direct2D1.Brush smallAreaBrushDx; SharpDX.Direct2D1.Brush textBrushDx; // for convenience, you can simply convert a WPF Brush to a DXBrush using the ToDxBrush() extension method provided by NinjaTrader // This is a common approach if you have a Brush property created e.g., on the UI you wish to use in custom rendering routines areaBrushDx = areaBrush.ToDxBrush(RenderTarget); smallAreaBrushDx = smallAreaBrush.ToDxBrush(RenderTarget); textBrushDx = textBrush.ToDxBrush(RenderTarget); // However - it should be noted that this conversion process can be rather expensive // If you have many brushes being created, and are not tied to WPF resources // You should rather favor creating the SharpDX Brush directly: // Warning: SolidColorBrush objects must be disposed of after they have been used SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.DodgerBlue); // 1.3 - Using The RenderTarget // before executing chart commands, you have the ability to describe how the RenderTarget should render // for example, we can store the existing RenderTarget AntialiasMode mode // then update the AntialiasMode to be the quality of non-text primitives are rendered SharpDX.Direct2D1.AntialiasMode oldAntialiasMode = RenderTarget.AntialiasMode; RenderTarget.AntialiasMode = SharpDX.Direct2D1.AntialiasMode.Aliased; // Note: The code above stores the oldAntialiasMode as a best practices // i.e., if you plan on changing a property of the RenderTarget, you should plan to set it back // This is to make sure your requirements to no interfere with the function of another script // Additionally smoothing has some performance impacts // Once you have defined all the necessary requirements for you object // You can execute a command on the RenderTarget to draw specific shapes // e.g., we can now use the RenderTarget's DrawLine() command to render a line // using the start/end points and areaBrushDx objects defined before RenderTarget.DrawLine(startPoint, endPoint, areaBrushDx, 4); // Since rendering occurs in a sequential fashion, after you have executed a command // you can switch a property of the RenderTarget to meet other requirements // For example, we can draw a second line now which uses a different AntialiasMode // and the changes render on the chart for both lines from the time they received commands RenderTarget.AntialiasMode = SharpDX.Direct2D1.AntialiasMode.PerPrimitive; RenderTarget.DrawLine(startPoint1, endPoint1, areaBrushDx, 4); // 1.4 - Rendering Custom Shapes // SharpDX namespace consists of several shapes you can use to draw objects more complicated than lines // For example, we can use the RectangleF object to draw a rectangle that covers the entire chart area SharpDX.RectangleF rect = new SharpDX.RectangleF(startPoint.X, startPoint.Y, width, height); // The RenderTarget consists of two commands related to Rectangles. // The FillRectangle() method is used to "Paint" the area of a Rectangle RenderTarget.FillRectangle(rect, areaBrushDx); // and DrawRectangle() is used to "Paint" the outline of a Rectangle RenderTarget.DrawRectangle(rect, customDXBrush, 2); // Another example is an ellipse which can be used to draw circles // The ellipse center point can be used from the Vectors calculated earlier // The width and height an absolute 100 device pixels // To ensure that pixel coordinates work across all DPI devices, we use the NinjaTrader ChartingExteions methods // Which will convert the "100" value from WPF pixels to Device Pixels both vertically and horizontally int ellipseRadiusY = ChartingExtensions.ConvertToVerticalPixels(100, ChartControl.PresentationSource); int ellipseRadiusX = ChartingExtensions.ConvertToHorizontalPixels(100, ChartControl.PresentationSource); SharpDX.Direct2D1.Ellipse ellipse = new SharpDX.Direct2D1.Ellipse(center, ellipseRadiusX, ellipseRadiusY); // 1.5 - Complex Brush Types and Shapes // For this ellipse, we can use one of the more complex brush types "RadialGradientBrush" // Warning: RadialGradientBrush objects must be disposed of after they have been used SharpDX.Direct2D1.RadialGradientBrush radialGradientBrush; // However creating a RadialGradientBrush requires a few more properties than SolidColorBrush // First, you need to define the array gradient stops the brush will eventually use SharpDX.Direct2D1.GradientStop[] gradientStops = new SharpDX.Direct2D1.GradientStop[2]; // With the gradientStops array, we can describe the color and position of the individual gradients gradientStops[0].Color = SharpDX.Color.Goldenrod; gradientStops[0].Position = 0.0f; gradientStops[1].Color = SharpDX.Color.SeaGreen; gradientStops[1].Position = 1.0f; // then declare a GradientStopCollection from our render target that uses the gradientStops array defined just before // Warning: GradientStopCollection objects must be disposed of after they have been used SharpDX.Direct2D1.GradientStopCollection gradientStopCollection = new SharpDX.Direct2D1.GradientStopCollection(RenderTarget, gradientStops); // we also need to tell our RadialGradientBrush to match the size and shape of the ellipse that we will be drawing // for convenience, SharpDX provides a RadialGradientBrushProperties structure to help define these properties SharpDX.Direct2D1.RadialGradientBrushProperties radialGradientBrushProperties = new SharpDX.Direct2D1.RadialGradientBrushProperties { GradientOriginOffset = new SharpDX.Vector2(0, 0), Center = ellipse.Point, RadiusX = ellipse.RadiusY, RadiusY = ellipse.RadiusY }; // we now have everything we need to create a radial gradient brush radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(RenderTarget, radialGradientBrushProperties, gradientStopCollection); // Finally, we can use this radialGradientBrush to "Paint" the area of the ellipse RenderTarget.FillEllipse(ellipse, radialGradientBrush); // 1.6 - Simple Text Rendering // For rendering custom text to the Chart, there are a few ways you can approach depending on your requirements // The most straight forward way is to "borrow" the existing chartControl font provided as a "SimpleFont" class // Using the chartControl LabelFont, your custom object will also change to the user defined properties allowing // your object to match different fonts if defined by user. // The code below will use the chartControl Properties Label Font if it exists, // or fall back to a default property if it cannot obtain that value NinjaTrader.Gui.Tools.SimpleFont simpleFont = chartControl.Properties.LabelFont ?? new NinjaTrader.Gui.Tools.SimpleFont("Arial", 12); // the advantage of using a SimpleFont is they are not only very easy to describe // but there is also a convenience method which can be used to convert the SimpleFont to a SharpDX.DirectWrite.TextFormat used to render to the chart // Warning: TextFormat objects must be disposed of after they have been used SharpDX.DirectWrite.TextFormat textFormat1 = simpleFont.ToDirectWriteTextFormat(); // Once you have the format of the font, you need to describe how the font needs to be laid out // Here we will create a new Vector2() which draws the font according to the to top left corner of the chart (offset by a few pixels) SharpDX.Vector2 upperTextPoint = new SharpDX.Vector2(ChartPanel.X + 10, ChartPanel.Y + 20); // Warning: TextLayout objects must be disposed of after they have been used SharpDX.DirectWrite.TextLayout textLayout1 = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, NinjaTrader.Custom.Resource.SampleCustomPlotUpperLeftCorner, textFormat1, ChartPanel.X + ChartPanel.W, textFormat1.FontSize); // With the format and layout of the text completed, we can now render the font to the chart RenderTarget.DrawTextLayout(upperTextPoint, textLayout1, textBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap); // 1.7 - Advanced Text Rendering // Font formatting and text layouts can get as complex as you need them to be // This example shows how to use a complete custom font unrelated to the existing user-defined chart control settings // Warning: TextLayout and TextFormat objects must be disposed of after they have been used SharpDX.DirectWrite.TextFormat textFormat2 = new SharpDX.DirectWrite.TextFormat(NinjaTrader.Core.Globals.DirectWriteFactory, "Century Gothic", FontWeight.Bold, FontStyle.Italic, 32f); SharpDX.DirectWrite.TextLayout textLayout2 = new SharpDX.DirectWrite.TextLayout(NinjaTrader.Core.Globals.DirectWriteFactory, NinjaTrader.Custom.Resource.SampleCustomPlotLowerRightCorner, textFormat2, 400, textFormat1.FontSize); // the textLayout object provides a way to measure the described font through a "Metrics" object // This allows you to create new vectors on the chart which are entirely dependent on the "text" that is being rendered // For example, we can create a rectangle that surrounds our font based off the textLayout which would dynamically change if the text used in the layout changed dynamically SharpDX.Vector2 lowerTextPoint = new SharpDX.Vector2(ChartPanel.W - textLayout2.Metrics.Width - 5, ChartPanel.Y + (ChartPanel.H - textLayout2.Metrics.Height)); SharpDX.RectangleF rect1 = new SharpDX.RectangleF(lowerTextPoint.X, lowerTextPoint.Y, textLayout2.Metrics.Width, textLayout2.Metrics.Height); // We can draw the Rectangle based on the TextLayout used above RenderTarget.FillRectangle(rect1, smallAreaBrushDx); RenderTarget.DrawRectangle(rect1, smallAreaBrushDx, 2); // And render the advanced text layout using the DrawTextLayout() method // Note: When drawing the same text repeatedly, using the DrawTextLayout() method is more efficient than using the DrawText() // because the text doesn't need to be formatted and the layout processed with each call RenderTarget.DrawTextLayout(lowerTextPoint, textLayout2, textBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap); // 1.8 - Cleanup // This concludes all of the rendering concepts used in the sample // However - there are some final clean up processes we should always provided before we are done // If changed, do not forget to set the AntialiasMode back to the default value as described above as a best practice RenderTarget.AntialiasMode = oldAntialiasMode; // We also need to make sure to dispose of every device dependent resource on each render pass // Failure to dispose of these resources will eventually result in unnecessary amounts of memory being used on the chart // Although the effects might not be obvious as first, if you see issues related to memory increasing over time // Objects such as these should be inspected first areaBrushDx.Dispose(); customDXBrush.Dispose(); gradientStopCollection.Dispose(); radialGradientBrush.Dispose(); smallAreaBrushDx.Dispose(); textBrushDx.Dispose(); textFormat1.Dispose(); textFormat2.Dispose(); textLayout1.Dispose(); textLayout2.Dispose(); } }
/// <summary> /// Draws the outline of the specified ellipse using the specified stroke style. /// </summary> /// <remarks> /// The {{DrawEllipse}} method doesn't return an error code if it fails. To determine whether a drawing operation (such as DrawEllipse) failed, check the result returned by the <see cref="M:SharpDX.Direct2D1.RenderTarget.EndDraw(System.Int64@,System.Int64@)" /> or <see cref="M:SharpDX.Direct2D1.RenderTarget.Flush(System.Int64@,System.Int64@)" /> methods. /// </remarks> /// <param name="ellipse">The position and radius of the ellipse to draw, in device-independent pixels. </param> /// <param name="brush">The brush used to paint the ellipse's outline. </param> /// <param name="strokeWidth">The thickness of the ellipse's stroke. The stroke is centered on the ellipse's outline. </param> /// <unmanaged>void ID2D1RenderTarget::DrawEllipse([In] const D2D1_ELLIPSE* ellipse,[In] ID2D1Brush* brush,[None] float strokeWidth,[In, Optional] ID2D1StrokeStyle* strokeStyle)</unmanaged> public void DrawEllipse(Ellipse ellipse, Brush brush, float strokeWidth) { DrawEllipse(ellipse, brush, strokeWidth, null); }
/// <summary> /// Paints the interior of the specified ellipse</summary> /// <param name="rect">The rectangle, in pixels, that encloses the ellipse to paint</param> /// <param name="brush">The brush used to paint the interior of the ellipse</param> public void FillEllipse(RectangleF rect, D2dBrush brush) { var tmpEllipse = new Ellipse { RadiusX = rect.Width * 0.5f, RadiusY = rect.Height * 0.5f }; tmpEllipse.Point = new Vector2(rect.X + tmpEllipse.RadiusX, rect.Y + tmpEllipse.RadiusY); m_renderTarget.FillEllipse(tmpEllipse, brush.NativeBrush); }
void RenderGeometry() { var ellipse = new Ellipse(new Vector2(100, 100), 3, 3); d2dDeviceContext.FillEllipse(ellipse, VertexFillBrush); d2dDeviceContext.DrawEllipse(ellipse, VertexDrawBrush, 0.5f); }