//--------------------------------------------------------------------------------------------------------- /// <summary> /// Изменение цветов кисти. /// Метод автоматически вызывается после установки соответствующих свойств /// </summary> //--------------------------------------------------------------------------------------------------------- protected virtual void RaiseColorChanged() { #if USE_WINDOWS System.Windows.Media.DrawingBrush hatch_brush = mWindowsBrush as System.Windows.Media.DrawingBrush; System.Windows.Media.DrawingGroup dg = hatch_brush.Drawing as System.Windows.Media.DrawingGroup; System.Windows.Media.GeometryDrawing gd = dg.Children[0] as System.Windows.Media.GeometryDrawing; if (mIsBackground) { gd.Brush = XWindowsColorManager.GetBrushByColor(mBackgroundColor); } else { gd.Brush = null; } gd.Pen.Brush = XWindowsColorManager.GetBrushByColor(mForegroundColor); // 2) Информируем об изменении NotifyPropertyChanged(PropertyArgsWindowsBrush); #endif #if USE_GDI if (mDrawingBrush != null) { mDrawingBrush.Dispose(); } mDrawingBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Cross, mForegroundColor, mBackgroundColor); #endif #if USE_SHARPDX if (mD2DBrush != null) { SharpDX.Direct2D1.SolidColorBrush d2d_solid_brush = mD2DBrush as SharpDX.Direct2D1.SolidColorBrush; d2d_solid_brush.Color = mForegroundColor; } #endif }
private void arrow(RawColor4 color) { float arrowLength = cp.ArrowLength; RawVector2[] points = new RawVector2[3]; points[0].X = EndPointX; points[0].Y = EndPointY; if (LineDirection.Vertical == axislineparam.Direction) { points[1].X = EndPointX - arrowLength / 2; points[1].Y = EndPointY + arrowLength; points[2].X = EndPointX + arrowLength / 2; points[2].Y = EndPointY + arrowLength; } else { points[1].X = EndPointX - arrowLength; points[1].Y = EndPointY + arrowLength / 2; points[2].X = EndPointX - arrowLength; points[2].Y = EndPointY - arrowLength / 2; } var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, color); cp._renderTarget.DrawLine(points[0], points[1], brush); cp._renderTarget.DrawLine(points[0], points[2], brush); DrawLegend(points[0].X, points[0].Y); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { var imageBrush = new ImageBrush(); imageBrush.ImageSource = _sisWrapper; rectangle.Fill = imageBrush; _sisWrapper.BeginDraw(); var context = new SharpDX.Direct2D1.DeviceContext(new IntPtr(_sisWrapper.GetDeviceContext())); context.Clear(new SharpDX.Color4(0.4f, 0.3f, 0.15f, 1.0f)); var random = new Random(); for (int i = 0; i < 20; ++i) { var brush = new SharpDX.Direct2D1.SolidColorBrush(context, new SharpDX.Color4( (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), 1.0f)); var left = (float)(250.0f * random.NextDouble()); var top = (float)(250.0f * random.NextDouble()); context.FillRectangle(new SharpDX.RectangleF( left, top, left + 50.0f, top + 50.0f), brush); } _sisWrapper.EndDraw(); }
/// <summary> /// 绘制标识 /// </summary> private void drawLegend() { var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, new RawColor4(0, 0, 1, 1)); var textformat = new SharpDX.DirectWrite.TextFormat(cp.dwFactory, "Arial", 12); foreach (var item in coordianteParamList) { if (item.lineDirection == LineDireciton.Horizontal) { for (int i = 0; i < item.scalePointList.Count; i++) { cp._renderTarget.DrawText((item.MinValue + i * item.Interval).ToString(), textformat, new RawRectangleF(item.scalePointList[i].Item2.X - 5, item.scalePointList[i].Item2.Y, item.scalePointList[i].Item2.X + 200, item.scalePointList[i].Item2.Y + 200), brush); } } else { if (item.lineLocation == LineLocation.Right) { for (int i = 0; i < item.scalePointList.Count; i++) { cp._renderTarget.DrawText((item.MinValue + i * item.Interval).ToString(), textformat, new RawRectangleF(item.scalePointList[i].Item2.X, item.scalePointList[i].Item2.Y - 8, item.scalePointList[i].Item2.X + 200, item.scalePointList[i].Item2.Y + 200), brush); } } else { for (int i = 0; i < item.scalePointList.Count; i++) { cp._renderTarget.DrawText((item.MinValue + i * item.Interval).ToString(), textformat, new RawRectangleF(item.scalePointList[i].Item2.X - 15, item.scalePointList[i].Item2.Y - 8, item.scalePointList[i].Item2.X + 200, item.scalePointList[i].Item2.Y), brush); } } } } }
/// <summary> /// Creates device-based resources to store a constant buffer, cube /// geometry, and vertex and pixel shaders. In some cases this will also /// store a geometry shader. /// </summary> public void CreateDeviceDependentResources() { ReleaseDeviceDependentResources(); // Create a default sampler state, which will use point sampling. pointSampler = ToDispose(new SamplerState(deviceResources.D3DDevice, new SamplerStateDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, BorderColor = new RawColor4(0, 0, 0, 0), ComparisonFunction = Comparison.Never, Filter = Filter.MinMagMipLinear, MaximumAnisotropy = 16, MaximumLod = float.MaxValue, MinimumLod = 0, MipLodBias = 0.0f })); // Create the texture that will be used as the offscreen render target. var textureDesc = new Texture2DDescription { Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, Width = textureWidth, Height = textureHeight, MipLevels = 1, ArraySize = 1, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default, CpuAccessFlags = CpuAccessFlags.None }; texture2D = new Texture2D(deviceResources.D3DDevice, textureDesc); // Create read and write views for the offscreen render target. shaderResourceView = new ShaderResourceView(deviceResources.D3DDevice, texture2D); renderTargetView = new RenderTargetView(deviceResources.D3DDevice, texture2D); // In this example, we are using D2D and DirectWrite; so, we need to create a D2D render target as well. SharpDX.Direct2D1.RenderTargetProperties props = new SharpDX.Direct2D1.RenderTargetProperties( SharpDX.Direct2D1.RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied), 96, 96, SharpDX.Direct2D1.RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); // The DXGI surface is used to create the render target. SharpDX.DXGI.Surface dxgiSurface = texture2D.QueryInterface <SharpDX.DXGI.Surface>(); d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(deviceResources.D2DFactory, dxgiSurface, props); // Create a solid color brush that will be used to render the text. whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, new RawColor4(1f, 1f, 1f, 1f)); // This is where we format the text that will be written on the render target. textFormat = new SharpDX.DirectWrite.TextFormat(deviceResources.DWriteFactory, "Consolas", SharpDX.DirectWrite.FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 64f); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; textFormat.ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center; }
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; }
public void FillEllipse(float x, float y, float width, float height, System.Drawing.Color clr) { SharpDX.Mathematics.Interop.RawVector2 center = new SharpDX.Mathematics.Interop.RawVector2(x, y); SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, ToColor(clr)); SharpDX.Direct2D1.Ellipse ellipse = new SharpDX.Direct2D1.Ellipse(center, width, height); d2dRenderTarget.FillEllipse(ellipse, brush); brush.Dispose(); }
public void DrawText(String message, String fontFamily, float fontSize, System.Drawing.Color clr, System.Drawing.Rectangle area) { SharpDX.DirectWrite.TextFormat fmt = new SharpDX.DirectWrite.TextFormat(dwFactory, fontFamily, fontSize); SharpDX.Mathematics.Interop.RawRectangleF rect = ToRectangle(area); SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, ToColor(clr)); d2dRenderTarget.DrawText(message, fmt, rect, brush); fmt.Dispose(); brush.Dispose(); }
private void drawLine() { var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, new RawColor4(0, 0, 1, 1)); foreach (var item in coordianteParamList) { RawVector2 pointS = new RawVector2(item.StartPointX, item.StartPointY); RawVector2 pointE = new RawVector2(item.EndPointX, item.EndPointY); cp._renderTarget.DrawLine(pointS, pointE, brush, item.LineWidth); } }
public SolidColorBrushImpl(ISolidColorBrush brush, SharpDX.Direct2D1.RenderTarget target) { PlatformBrush = new SharpDX.Direct2D1.SolidColorBrush( target, brush?.Color.ToDirect2D() ?? new SharpDX.Mathematics.Interop.RawColor4(), new SharpDX.Direct2D1.BrushProperties { Opacity = brush != null ? (float)brush.Opacity : 1.0f, Transform = target.Transform } ); }
public SolidColorBrushImpl(Perspex.Media.SolidColorBrush brush, SharpDX.Direct2D1.RenderTarget target) { PlatformBrush = new SharpDX.Direct2D1.SolidColorBrush( target, brush?.Color.ToDirect2D() ?? new SharpDX.Color4(), new SharpDX.Direct2D1.BrushProperties { Opacity = brush != null ? (float)brush.Opacity : 1.0f, Transform = target.Transform } ); }
/// <summary> /// Direct2D has no ConicGradient implementation so fall back to a solid colour brush based on /// the first gradient stop. /// </summary> public SolidColorBrushImpl(IConicGradientBrush brush, SharpDX.Direct2D1.DeviceContext target) { PlatformBrush = new SharpDX.Direct2D1.SolidColorBrush( target, brush?.GradientStops[0].Color.ToDirect2D() ?? new SharpDX.Mathematics.Interop.RawColor4(), new SharpDX.Direct2D1.BrushProperties { Opacity = brush != null ? (float)brush.Opacity : 1.0f, Transform = target.Transform } ); }
public void Draw(SharpDX.Direct2D1.DeviceContext context, RectangleF rect) { if (_brush == null) { _brush = new SharpDX.Direct2D1.SolidColorBrush(context, Color4.White); } context.Clear(Color4.Black); context.Transform = Matrix3x2.Identity; DrawText(context, rect, $"Draw: {count++}", "Verdana", 24, TextAlignment.Trailing, ParagraphAlignment.Near); //device.D2DDeviceContext.FillEllipse(new Ellipse(new Vector2(_rect.MouseX, _rect.MouseY), 50.0f, 50.0f), _brush); }
public SolidColourElementState(SolidColourElementState existing, SolidColourElement other, RenderContext context) { props = other.Props; brush = existing?.brush ?? new SharpDX.Direct2D1.SolidColorBrush(Renderer.AssertRendererType(context.Renderer).d2dTarget, new SharpDX.Mathematics.Interop.RawColor4 { R = other.Props.Colour.R, G = other.Props.Colour.G, B = other.Props.Colour.B, A = other.Props.Colour.A }); context.Disposables.Add(brush); boundingBox = other.Props.Location != null?other.Props.Location(context.Bounds) : context.Bounds; }
public void DrawLine(float x0, float y0, float x1, float y1, System.Drawing.Color clr) { SharpDX.Mathematics.Interop.RawVector2 p0 = new SharpDX.Mathematics.Interop.RawVector2 { X = x0, Y = y0 }; SharpDX.Mathematics.Interop.RawVector2 p1 = new SharpDX.Mathematics.Interop.RawVector2 { X = x1, Y = y1 }; SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, ToColor(clr)); d2dRenderTarget.DrawLine(p0, p1, brush); brush.Dispose(); }
private Font(string pFamily, float pSize, Color pColor, IGraphicsAdapter pAdapter) { if (pAdapter.Method == RenderMethods.DirectX) { var dx = (DirectXAdapter)pAdapter; _factory = dx.FactoryDWrite; Format = new TextFormat(dx.FactoryDWrite, pFamily, pSize); Brush = new SharpDX.Direct2D1.SolidColorBrush(dx.Context, pColor); } else { throw new NotImplementedException(); } }
public void FillRectangle(float x, float y, float width, float height, System.Drawing.Color clr) { SharpDX.Mathematics.Interop.RawRectangleF rect = new SharpDX.Mathematics.Interop.RawRectangleF { Left = x, Top = y, Right = x + width, Bottom = y + height }; SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(d2dRenderTarget, ToColor(clr)); d2dRenderTarget.FillRectangle(rect, brush); brush.Dispose(); }
public void Dispose() { if (_brush != null) { _brush.Dispose(); _brush = null; } if (_format != null) { _format.Dispose(); _format = null; } }
private void InitializeDirectXResources() { var clientSize = ClientSize; var backBufferDesc = new SharpDX.DXGI.ModeDescription(clientSize.Width, clientSize.Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm); var swapChainDesc = new SharpDX.DXGI.SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), Usage = SharpDX.DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = Handle, SwapEffect = SharpDX.DXGI.SwapEffect.Discard, IsWindowed = false }; SharpDX.Direct3D11.Device.CreateWithSwapChain(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, new[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, swapChainDesc, out _d3DDevice, out var swapChain); _d3DDeviceContext = _d3DDevice.ImmediateContext; _swapChain = new SharpDX.DXGI.SwapChain1(swapChain.NativePointer); _d2DFactory = new SharpDX.Direct2D1.Factory(); using (var backBuffer = _swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0)) { _renderTargetView = new SharpDX.Direct3D11.RenderTargetView(_d3DDevice, backBuffer); _renderTarget = new SharpDX.Direct2D1.RenderTarget(_d2DFactory, backBuffer.QueryInterface <SharpDX.DXGI.Surface>(), new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied))) { TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype }; } _solidColorBrush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, Color.White); _dwFactory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared); _textFormat = new SharpDX.DirectWrite.TextFormat(_dwFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 84 * (float)GraphicsUtils.Scale) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center }; // var rectangleGeometry = new D2D1.RoundedRectangleGeometry(_d2DFactory, // new D2D1.RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, Width - 128 * 2, Height - 128 * 2) }); }
/// <summary> /// 绘制刻度线 /// </summary> private void drawScale() { var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, new RawColor4(0, 0, 1, 1)); var strokeStyleProperties = new SharpDX.Direct2D1.StrokeStyleProperties(); strokeStyleProperties.DashStyle = SharpDX.Direct2D1.DashStyle.Custom; float[] dashes = { 10, 5 }; var strokeStyle = new SharpDX.Direct2D1.StrokeStyle(cp.factory, strokeStyleProperties, dashes); foreach (var item in coordianteParamList) { foreach (var C in item.scalePointList) { cp._renderTarget.DrawLine(C.Item1, C.Item2, brush, item.LineWidth); //是否显示虚线 if (item.virtualLineVisible == VirtualLineVisible.Visible) { if (item.lineDirection == LineDireciton.Horizontal) { RawVector2 rv = new RawVector2(); rv.X = C.Item1.X; rv.Y = C.Item1.Y - VLength; cp._renderTarget.DrawLine(C.Item1, rv, brush, 0.5F, strokeStyle); } else { if (item.lineLocation == LineLocation.Right) { RawVector2 rv = new RawVector2(); rv.X = C.Item1.X - HLength - item.Index * LineInterval; rv.Y = C.Item1.Y; cp._renderTarget.DrawLine(C.Item1, rv, brush, 0.5F, strokeStyle); } else { RawVector2 rv = new RawVector2(); rv.X = C.Item1.X + HLength; rv.Y = C.Item1.Y; cp._renderTarget.DrawLine(C.Item1, rv, brush, 0.5F, strokeStyle); } } } } } }
public void Render(Pipeline.Pipeline pipeline, Pipeline.PipelineAssets pipelineAssets) { PopulateCommandList(pipeline, pipelineAssets); pipeline.CommandQueue.ExecuteCommandList(pipelineAssets.CommandList); var brush = new SharpDX.Direct2D1.SolidColorBrush(pipeline.D2DRenderTargets[0], SharpDX.Color4.White); pipeline.D3D11On12Device.AcquireWrappedResources(new SharpDX.Direct3D11.Resource[] { pipeline.WrappedBackBuffers[pipeline.FrameIndex] }, 1); pipeline.D2DRenderTargets[pipeline.FrameIndex].BeginDraw(); pipeline.D2DRenderTargets[pipeline.FrameIndex].FillRectangle(new SharpDX.Mathematics.Interop.RawRectangleF(5f, 5f, 100f, 100f), brush); // textBrush.Color = Color4.Lerp(colors[t], colors[t + 1], f); // pipeline.D2DRenderTargets[pipeline.FrameIndex].DrawText("Hello Text", textFormat, new SharpDX.Mathematics.Interop.RawRectangleF((float)Math.Sin(Environment.TickCount / 1000.0F) * 200 + 400, 10, 2000, 500), textBrush); pipeline.D2DRenderTargets[pipeline.FrameIndex].EndDraw(); pipeline.D3D11On12Device.ReleaseWrappedResources(new SharpDX.Direct3D11.Resource[] { pipeline.WrappedBackBuffers[pipeline.FrameIndex] }, 1); pipeline.D3D11Device.ImmediateContext.Flush(); brush.Dispose(); pipeline.SwapChain3.Present(1, 0); pipeline.MoveToNextFrame(); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Изменение цвета кисти. /// Метод автоматически вызывается после установки соответствующего свойства /// </summary> //--------------------------------------------------------------------------------------------------------- protected virtual void RaiseColorChanged() { #if USE_WINDOWS System.Windows.Media.SolidColorBrush solid_brush = mWindowsBrush as System.Windows.Media.SolidColorBrush; solid_brush.Color = Color; // 2) Информируем об изменении NotifyPropertyChanged(PropertyArgsWindowsBrush); #endif #if USE_GDI System.Drawing.SolidBrush gdi_solid_brush = mDrawingBrush as System.Drawing.SolidBrush; gdi_solid_brush.Color = Color; #endif #if USE_SHARPDX if (mD2DBrush != null) { SharpDX.Direct2D1.SolidColorBrush d2d_solid_brush = mD2DBrush as SharpDX.Direct2D1.SolidColorBrush; d2d_solid_brush.Color = mColor; } #endif }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Обновление ресурса Direct2D /// </summary> /// <param name="forced">Принудительное создание ресурса Direct2D</param> //--------------------------------------------------------------------------------------------------------- public override void UpdateDirect2DResource(Boolean forced = false) { if (XDirect2DManager.D2DRenderTarget != null) { // Принудительное создание ресурса if (forced) { XDisposer.SafeDispose(ref mD2DBrush); } if (mD2DBrush == null) { mD2DBrush = new SharpDX.Direct2D1.SolidColorBrush(XDirect2DManager.D2DRenderTarget, mColor); } else { SharpDX.Direct2D1.SolidColorBrush d2d_solid_brush = mD2DBrush as SharpDX.Direct2D1.SolidColorBrush; d2d_solid_brush.Color = mColor; } } }
private void DrawLegend(float PointX, float PointY) { float unitX = 0; float unitY = 0; var unitbrush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, new RawColor4(0, 0, 0, 1)); var textformat = new SharpDX.DirectWrite.TextFormat(cp.dwFactory, "Arial", 12); unitX = PointX; unitY = PointY; if (axislineparam.lineLocation == LineLocation.Left) { unitX = PointX - 30; unitY = PointY + 2; } if (axislineparam.Direction == LineDirection.Horizontal) { unitX = PointX - 20; unitY = PointY + 2; } cp._renderTarget.DrawText(axislineparam.Caption, textformat, new RawRectangleF(unitX, unitY, unitX + 200, unitY + 200), unitbrush); }
private void Window_Loaded(object sender, RoutedEventArgs e) { Dispatcher.BeginInvoke(new Action(() => { renderFrame.Height = (int)(this.Content as Grid).RenderSize.Height; renderFrame.Width = (int)(this.Content as Grid).RenderSize.Width; renderFrame.RenderTargetChanged += RenderFrame_RenderTargetChanged; //renderFrame.DisplayHandle = Handle; renderFrame.Initialize(); TargetImage.Source = imageSource; BackgroundColor = Interop.MediaColorToNativeColor((Background as SolidColorBrush).Color); Clear = renderFrame.CreateDrawCommnad2D <Clear2DCommand>(); Clear.clearColor = BackgroundColor; SharpDX.Direct2D1.Ellipse ellipse = new SharpDX.Direct2D1.Ellipse(new SharpDX.Mathematics.Interop.RawVector2(100, 100), 50, 50); EllipseBrush = renderFrame.Controller.CreateSolidColorBrush(SharpDX.Color.Black); DrawEllipse = renderFrame.CreateDrawCommnad2D <DrawEllipse2DCommand>(); DrawEllipse.ellipse = ellipse; DrawEllipse.brush = EllipseBrush; FillEllipse = renderFrame.CreateDrawCommnad2D <FillEllipse2DCommand>(); FillEllipse.ellipse = ellipse; FillEllipse.brush = EllipseBrush; DrawLine = renderFrame.CreateDrawCommnad2D <DrawLine2DCommand>(); DrawLine.point0 = new SharpDX.Mathematics.Interop.RawVector2(0, 0); DrawLine.point1 = new SharpDX.Mathematics.Interop.RawVector2(100, 100); DrawLine.strokeWidth = 10; DrawLine.brush = EllipseBrush; System.Windows.Media.CompositionTarget.Rendering += OnRendering; //dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); //dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 16); //dispatcherTimer.Start(); })); }
protected override void OnRender(ChartControl chartControl, ChartScale chartScale) { for (int index = ChartBars.FromIndex; index <= ChartBars.ToIndex; index++) { // gets the pixel coordinate of the bar index passed to the method - X axis float xStart = chartControl.GetXByBarIndex(ChartBars, index); // gets the pixel coordinate of the price value passed to the method - Y axis float yStart = chartScale.GetYByValue(High.GetValueAt(index) + 2 * TickSize); float width = (float)chartControl.BarWidth * 4; // construct the rectangleF struct to describe the position and size the drawing SharpDX.RectangleF rect = new SharpDX.RectangleF(xStart, yStart, width, width); // // define the brush used in the rectangle SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Blue); SharpDX.Direct2D1.SolidColorBrush outlineBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Black); // The RenderTarget consists of two commands related to Rectangles. // The FillRectangle() method is used to "Paint" the area of a Rectangle // execute the render target fill rectangle with desired values RenderTarget.FillRectangle(rect, customDXBrush); // and DrawRectangle() is used to "Paint" the outline of a Rectangle RenderTarget.DrawRectangle(rect, outlineBrush, 2); //Added WH 6/5/2017 // always dispose of a brush when finished customDXBrush.Dispose(); outlineBrush.Dispose(); } base.OnRender(chartControl, chartScale); }
public override void Draw() { calculate(); if (listpointE.Count == 0) { return; } var textformat = new SharpDX.DirectWrite.TextFormat(cp.dwFactory, "Arial", 12); var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, color); string strValue = ""; float showVlaue = 0; for (int i = 0; i < (ScaleCount + 1); i++) { cp._renderTarget.DrawLine(listpointS[i], listpointE[i], brush, 1); if (lp.Direction == LineDirection.Vertical) { showVlaue = lp.MinScale + i * lp.CellScale; if (lp.lineLocation == LineLocation.Left) { textformat.FlowDirection = FlowDirection.TopToBottom; textformat.ReadingDirection = ReadingDirection.RightToLeft; strValue = showVlaue < 0 ? Math.Abs(showVlaue).ToString() + "-" : (showVlaue).ToString(); //cp._renderTarget.DrawText(strValue, textformat, new RawRectangleF(listpointE[i].X-cp.ScalePadding-200, listpointE[i].Y-7-200, listpointE[i].X - cp.ScalePadding, listpointE[i].Y - 7),brush); cp._renderTarget.DrawText(strValue, textformat, new RawRectangleF(listpointE[i].X - cp.ScalePadding - 200, listpointE[i].Y - 7 + 200, listpointE[i].X - cp.ScalePadding, listpointE[i].Y - 7), brush); } else { cp._renderTarget.DrawText(showVlaue.ToString(), textformat, new RawRectangleF(listpointE[i].X + cp.ScalePadding, listpointE[i].Y - 7, listpointE[i].X + cp.ScalePadding + 1200, listpointE[i].Y - 7 + 1200), brush); } } else { cp._renderTarget.DrawText((lp.MinScale + i * lp.CellScale).ToString(), textformat, new RawRectangleF(listpointE[i].X - cp.ScalePadding - 4, listpointE[i].Y, listpointE[i].X + 1200, listpointE[i].Y + 1200), brush); } } }
public override void Draw() { if (axislineparam.lineVisible == LineVisiable.Hide) { return; } calculate(); RawVector2 rs = new RawVector2(StartPointX, StartPointY); RawVector2 re = new RawVector2(EndPointX, EndPointY); var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, color); cp._renderTarget.DrawLine(rs, re, brush, 0.5F); arrow(color); if (ShowVirtualLine.Visible == axislineparam.showVirtualLine)//绘制虚线 { VirtualLine vl = new VirtualLine(cp, axislineparam); vl.color = color; vl.Draw(); } LineScale ls = new LineScale(cp, axislineparam);//刻度线 ls.color = color; ls.Draw(); }
public override void DrawRectangle(Pen pen, float x, float y, float width, float height) { using (var brush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, pen.Color.ToColor4())) { _renderTarget.DrawRectangle(new SharpDX.RectangleF(x, y, width, height), brush); } }
private void DirectXRender(List<UIElement> points) { if (points.Count <= 0) return; Line initLine = points[0] as Line; Point p1 = new Point ( Math.Min(initLine.X1 - initLine.StrokeThickness / 2, initLine.X2 - initLine.StrokeThickness / 2), Math.Min(initLine.Y1 - initLine.StrokeThickness / 2, initLine.Y2 - initLine.StrokeThickness / 2) ), p2 = new Point ( Math.Max(initLine.X1 + initLine.StrokeThickness / 2, initLine.X2 + initLine.StrokeThickness / 2), Math.Max(initLine.Y1 + initLine.StrokeThickness / 2, initLine.Y2 + initLine.StrokeThickness / 2) ); foreach (var child in points) { var line = child as Line; if (line == null) continue; if (p1.X > line.X1 - line.StrokeThickness / 2) p1.X = line.X1 - line.StrokeThickness / 2; if (p1.X > line.X2 - line.StrokeThickness / 2) p1.X = line.X2 - line.StrokeThickness / 2; if (p2.X < line.X1 + line.StrokeThickness / 2) p2.X = line.X1 + line.StrokeThickness / 2; if (p2.X < line.X2 + line.StrokeThickness / 2) p2.X = line.X2 + line.StrokeThickness / 2; if (p1.Y > line.Y1 - line.StrokeThickness / 2) p1.Y = line.Y1 - line.StrokeThickness / 2; if (p1.Y > line.Y2 - line.StrokeThickness / 2) p1.Y = line.Y2 - line.StrokeThickness / 2; if (p2.Y < line.Y1 + line.StrokeThickness / 2) p2.Y = line.Y1 + line.StrokeThickness / 2; if (p2.Y < line.Y2 + line.StrokeThickness / 2) p2.Y = line.Y2 + line.StrokeThickness / 2; } var bndRect = new Rect(p1, p2); var dxTarget = new SurfaceImageSource ( (int)(bndRect.Width * DisplayProperties.LogicalDpi / 96.0 + 1), (int)(bndRect.Height * DisplayProperties.LogicalDpi / 96.0 + 1) ); SharpDX.DXGI.ISurfaceImageSourceNative dxTargetNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNative>(dxTarget); dxTargetNative.Device = d3dDevice.QueryInterface<SharpDX.DXGI.Device>(); /* * Draw Logic */ SharpDX.DrawingPoint drawingPoint; var surface = dxTargetNative.BeginDraw(new SharpDX.Rectangle(0, 0, (int)(bndRect.Width * DisplayProperties.LogicalDpi / 96.0 + 1), (int)(bndRect.Height * DisplayProperties.LogicalDpi / 96.0 + 1)), out drawingPoint); var dxRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, surface, new SharpDX.Direct2D1.RenderTargetProperties() { DpiX = DisplayProperties.LogicalDpi, DpiY = DisplayProperties.LogicalDpi, PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), Type = SharpDX.Direct2D1.RenderTargetType.Default, Usage = SharpDX.Direct2D1.RenderTargetUsage.None }); dxRenderTarget.BeginDraw(); dxRenderTarget.Clear(SharpDX.Color.Transparent); foreach (var child in points) { var line = child as Line; if (line == null) continue; Color c = (line.Stroke as SolidColorBrush).Color; var brush = new SharpDX.Direct2D1.SolidColorBrush(dxRenderTarget, new SharpDX.Color(c.R, c.G, c.B, c.A)); var style = new SharpDX.Direct2D1.StrokeStyleProperties(); style.LineJoin = SharpDX.Direct2D1.LineJoin.Round; style.StartCap = SharpDX.Direct2D1.CapStyle.Round; style.EndCap = SharpDX.Direct2D1.CapStyle.Round; var stroke = new SharpDX.Direct2D1.StrokeStyle(d2dFactory, style); dxRenderTarget.DrawLine( new SharpDX.DrawingPointF((float)(line.X1 - bndRect.Left), (float)(line.Y1 - bndRect.Top)), new SharpDX.DrawingPointF((float)(line.X2 - bndRect.Left), (float)(line.Y2 - bndRect.Top)), brush, (float)line.StrokeThickness, stroke); } dxRenderTarget.EndDraw(); dxTargetNative.EndDraw(); var dxImage = new Image(); dxImage.Source = dxTarget; canvas.Children.Add(dxImage); Canvas.SetLeft(dxImage, bndRect.X); Canvas.SetTop(dxImage, bndRect.Y); }
protected override void OnPaint(PaintEventArgs e) { lock (bufferLock) { try { var gifEmotesOnScreen = new List <GifEmoteState>(); if (buffer == null) { buffer = context.Allocate(e.Graphics, ClientRectangle); } var g = buffer.Graphics; //var g = e.Graphics; g.Clear((App.ColorScheme.ChatBackground as SolidBrush).Color); var borderPen = Selected ? App.ColorScheme.ChatBorderFocused : App.ColorScheme.ChatBorder; g.SmoothingMode = SmoothingMode.AntiAlias; // DRAW MESSAGES var M = GetMessagesClone(); if (M != null && M.Length > 0) { var startIndex = Math.Max(0, (int)_scroll.Value); if (startIndex < M.Length) { var yStart = MessagePadding.Top - (int)(M[startIndex].Height * (_scroll.Value % 1)); var h = Height - MessagePadding.Top - MessagePadding.Bottom; if (startIndex < M.Length) { var y = yStart; //for (int i = 0; i < startIndex; i++) //{ // M[i].IsVisible = false; //} for (var i = startIndex; i < M.Length; i++) { var msg = M[i]; //msg.IsVisible = true; MessageRenderer.DrawMessage(g, msg, MessagePadding.Left, y, selection, i, !App.UseDirectX, gifEmotesOnScreen, allowMessageSeperator: AllowMessageSeperator); if (y - msg.Height > h) { //for (; i < M.Length; i++) //{ // M[i].IsVisible = false; //} break; } y += msg.Height; if (AppSettings.ChatShowLastReadMessageIndicator && LastReadMessage == msg && i != M.Length - 1) { g.FillRectangle(lastReadMessageBrush, 0, y, Width, 1); } } GifEmotesOnScreen = gifEmotesOnScreen; } if (App.UseDirectX) { SharpDX.Direct2D1.DeviceContextRenderTarget renderTarget = null; var dc = g.GetHdc(); renderTarget = new SharpDX.Direct2D1.DeviceContextRenderTarget(MessageRenderer.D2D1Factory, MessageRenderer.RenderTargetProperties); renderTarget.BindDeviceContext(dc, new RawRectangle(0, 0, Width, Height)); renderTarget.BeginDraw(); //renderTarget.TextRenderingParams = new SharpDX.DirectWrite.RenderingParams(Fonts.Factory, 1, 1, 1, SharpDX.DirectWrite.PixelGeometry.Flat, SharpDX.DirectWrite.RenderingMode.CleartypeGdiClassic); renderTarget.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale; var y = yStart; var brushes = new Dictionary <RawColor4, SCB>(); var textColor = App.ColorScheme.Text; var textBrush = new SCB(renderTarget, new RawColor4(textColor.R / 255f, textColor.G / 255f, textColor.B / 255f, 1)); for (var i = startIndex; i < M.Length; i++) { var msg = M[i]; foreach (var word in msg.Words) { if (word.Type == SpanType.Text) { SCB brush; if (word.Color == null) { brush = textBrush; } else { var hsl = word.Color.Value; if (App.ColorScheme.IsLightTheme) { if (hsl.Saturation > 0.4f) { hsl = hsl.WithSaturation(0.4f); } if (hsl.Luminosity > 0.5f) { hsl = hsl.WithLuminosity(0.5f); } } else { if (hsl.Luminosity < 0.5f) { hsl = hsl.WithLuminosity(0.5f); } if (hsl.Luminosity < 0.6f && hsl.Hue > 0.54444 && hsl.Hue < 0.8333) { hsl = hsl.WithLuminosity(hsl.Luminosity + (float)Math.Sin((hsl.Hue - 0.54444) / (0.8333 - 0.54444) * Math.PI) * hsl.Saturation * 0.2f); } if (hsl.Luminosity < 0.8f && (hsl.Hue < 0.06 || hsl.Hue > 0.92)) { hsl = hsl.WithLuminosity(hsl.Luminosity + (msg.HasAnyHighlightType(HighlightType.Highlighted) ? 0.27f : 0.1f) * hsl.Saturation); } } if (hsl.Luminosity >= 0.95f) { hsl = hsl.WithLuminosity(0.95f); } float r, _g, b; hsl.ToRGB(out r, out _g, out b); var color = new RawColor4(r, _g, b, 1f); if (!brushes.TryGetValue(color, out brush)) { brushes[color] = brush = new SCB(renderTarget, color); } } if (word.SplitSegments == null) { renderTarget.DrawText((string)word.Value, Fonts.GetTextFormat(word.Font), new RawRectangleF(MessagePadding.Left + word.X, y + word.Y, 10000, 10000), brush); } else { foreach (var split in word.SplitSegments) { renderTarget.DrawText(split.Item1, Fonts.GetTextFormat(word.Font), new RawRectangleF(MessagePadding.Left + split.Item2.X, y + split.Item2.Y, 10000, 10000), brush); } } } } if (y - msg.Height > h) { break; } y += msg.Height; } foreach (var b in brushes.Values) { b.Dispose(); } renderTarget.EndDraw(); textBrush.Dispose(); g.ReleaseHdc(dc); renderTarget.Dispose(); } { var y = yStart; Brush disabledBrush = new SolidBrush(Color.FromArgb(172, (App.ColorScheme.ChatBackground as SolidBrush)?.Color ?? Color.Black)); for (var i = startIndex; i < M.Length; i++) { var msg = M[i]; if (msg.Disabled) { g.SmoothingMode = SmoothingMode.None; g.FillRectangle(disabledBrush, 0, y + 1, Width, msg.Height - 1); } if (y - msg.Height > h) { break; } y += msg.Height; } disabledBrush.Dispose(); } } } g.DrawRectangle(borderPen, 0, 0, Width - 1, Height - 1); OnPaintOnBuffer(g); buffer.Render(e.Graphics); } catch (Exception exc) { exc.Log("graphics"); } } }
// enum PositionDX { // Left, Center, Right; // } private void drawHistogram(List <double> list, string position, string title) { if (list.Count < 2) { return; } SharpDX.Vector2 startPoint; SharpDX.Vector2 endPoint; float leadingSpace = 30.0f; //Print(ChartPanel.W); if (position == "Center") { leadingSpace = ChartPanel.W / 2; } if (position == "Right") { leadingSpace = ChartPanel.W - (ChartPanel.W / 4); } float halfHeight = ChartPanel.H / 4; float maxWidth = ChartPanel.W / 8; Dictionary <double, double> Profile = listIntoSortedDict(list: list); var mode = Profile.OrderByDescending(x => x.Value).FirstOrDefault().Key; List <double> arr = iBRanges; int avg = Convert.ToInt32(arr.Average()); double stdDev = StandardDeviation(values: arr); double stDevLo = mode - stdDev; if (stDevLo < 3) { stDevLo = 3; } double stDevHi = mode + stdDev; if (!IsInHitTest) { SharpDX.Direct2D1.Brush areaBrushDx; areaBrushDx = areaBrush.ToDxBrush(RenderTarget); SharpDX.Direct2D1.SolidColorBrush pocBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Red); SharpDX.Direct2D1.SolidColorBrush avgBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Goldenrod); SharpDX.Direct2D1.SolidColorBrush volBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Gray); int spacer = 20; float divisor = maxWidth / (float)Profile.Values.Max(); textFormat = new TextFormat(Globals.DirectWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, textSize) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Trailing, //TextAlignment.Leading, WordWrapping = WordWrapping.NoWrap }; textFormatSmaller = new TextFormat(Globals.DirectWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, textSize) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Trailing, //TextAlignment.Leading, WordWrapping = WordWrapping.NoWrap }; SharpDX.Direct2D1.Brush textBrushDx; textBrushDx = textBrush.ToDxBrush(RenderTarget); string unicodeString = "today"; foreach (KeyValuePair <double, double> row in Profile) { //Print(row.Value); float rowSize = (float)row.Value * divisor; spacer += 15; startPoint = new SharpDX.Vector2(ChartPanel.X + leadingSpace, halfHeight + spacer); endPoint = new SharpDX.Vector2(ChartPanel.X + rowSize + leadingSpace, halfHeight + spacer); if (row.Key == mode) { areaBrushDx = pocBrush; } else if (row.Key == avg) { areaBrushDx = avgBrush; } else if (row.Key < stDevLo || row.Key > stDevHi) { areaBrushDx = volBrush; } else { areaBrushDx = areaBrush.ToDxBrush(RenderTarget); } drawRow(startPoint: startPoint, endPoint: endPoint, areaBrushDx: areaBrushDx); // recurrence text if ((int)row.Key == (int)ibRange) { float textStartPos = (float)startPoint.Y - 10f; float endPointIB = 35f + (float)ibRange; SharpDX.RectangleF rect = new SharpDX.RectangleF(0f, textStartPos, endPoint.X + endPointIB, 10f); RenderTarget.DrawText("today", textFormatSmaller, rect, areaBrushDx); } if (row.Key == mode) { float commonBuffer = 40f; if ((int)row.Key == (int)ibRange) { commonBuffer += 40f; } float textStartPos = (float)startPoint.Y - 10f; SharpDX.RectangleF rect = new SharpDX.RectangleF(0f, textStartPos, endPoint.X + commonBuffer, 10f); RenderTarget.DrawText("poc", textFormatSmaller, rect, areaBrushDx); } if (row.Key == avg) { float commonBuffer = 40f; if ((int)row.Key == (int)ibRange) { commonBuffer += 40f; } if ((int)row.Key == (int)mode) { commonBuffer += 40f; } float textStartPos = (float)startPoint.Y - 10f; SharpDX.RectangleF rect = new SharpDX.RectangleF(0f, textStartPos, endPoint.X + commonBuffer, 10f); RenderTarget.DrawText("avg", textFormatSmaller, rect, areaBrushDx); } // value text float textStartPos2 = (float)startPoint.Y - 10f; SharpDX.RectangleF rect2 = new SharpDX.RectangleF(0f, textStartPos2, leadingSpace - 5f, 10f); RenderTarget.DrawText(string.Format("{0}", row.Key), textFormat, rect2, areaBrushDx); } // end text //areaBrushDx = areaBrush.ToDxBrush(RenderTarget); SharpDX.RectangleF rect3 = new SharpDX.RectangleF(0f, halfHeight + spacer + 15f, 245, 10f); RenderTarget.DrawText(dayCount + " day " + title + " distribution", textFormat, rect3, areaBrushDx); areaBrushDx.Dispose(); textBrushDx.Dispose(); pocBrush.Dispose(); avgBrush.Dispose(); volBrush.Dispose(); } }
public void Initialize(CommonDX.DeviceManager deviceManager) { _deviceManager = deviceManager; _d2dContext = deviceManager.ContextDirect2D; _generalGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Gray); _generalRedColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Red); _generalLightGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.LightGray); _generalLightWhiteColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.White); _generalTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 16f); _debugTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 20f); _layoutDetail = new LayoutDetail() { Width = this.State.DrawingSurfaceWidth, Height = this.State.DrawingSurfaceHeight }; _layoutDeviceScreenSize = new RectangleF(0, 0, (float)_layoutDetail.Width, (float)_layoutDetail.Height); _appWidth = (float)_layoutDetail.Width + 5; _appHeight = (float)_layoutDetail.Height; _updateScaleTranslate(1.0f); ////_drawTiles(0); if (State.DefaultBackgroundUri != string.Empty) { _clearRenderTree(); _changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, State.DefaultBackgroundFolder, State.DefaultBackgroundUri, "", Color.White, 0.7f, "", false); } //GestureService.OnGestureRaised += (o,a) => { // CustomGestureArgs gestureArgs = (CustomGestureArgs)a; // //NumberFramesToRender += 3; // if (gestureArgs.ManipulationStartedArgs != null) // { // _isInertialTranslationStaging = false; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationInertiaStartingArgs != null) // { // _isInertialTranslationStaging = true; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationUpdatedArgs != null) // { // if(_isInertialTranslationStaging) // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Velocities.Linear.X); // else // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Cumulative.Translation.X); // } // else if (gestureArgs.ManipulationCompletedArgs != null) // { // if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale < 1) // { // if (_globalScale.X != 0.9f) { _updateBackgroundTweener(1.0f, 0.9f, 1.2f); SendInformationNotification("zoom level at 90%", 3); } // //_updateScaleTranslate(0.9f); // } // else if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale > 1) // { // if (_globalScale.X != 1.0f) { _updateBackgroundTweener(0.9f, 1.0f, 1.2f); SendInformationNotification("zoom level at 100%", 3); } // //_updateScaleTranslate(1.0f); // } // _globalCameraTranslation = _globalCameraTranslation + _globalCameraTranslationStaging; // _globalCameraTranslationStaging = Vector3.Zero; // _isInertialTranslationStaging = false; // } // else if (gestureArgs.TappedEventArgs != null) // { // var x = gestureArgs.TappedEventArgs.Position.X - _globalCameraTranslation.X; // var y = gestureArgs.TappedEventArgs.Position.Y - _globalCameraTranslation.Y; // var found = _doTilesHitTest((float)x, (float)y); // if (found != null && found.Count > 0) // { // _selectedRect = found[0]; // } // else _selectedRect = null; // } //}; WindowLayoutService.OnWindowLayoutRaised += WindowLayoutService_OnWindowLayoutRaised; }
public object Convert(object value, Type targetType, object parameter, string language) { MyChildRenderItem.RenderDataStruct Item = (MyChildRenderItem.RenderDataStruct)value; if (Item.FontSize != AppSettings.dFontSize) { Item.sizeFunc(); //cannot react this late Item = (MyChildRenderItem.RenderDataStruct)value; } int pixelWidth = (int)Item.Width, pixelHeight = (int)Item.Height; SurfaceImageSource newSource = new SurfaceImageSource(pixelWidth, pixelHeight, false); //SharpDX.Direct3D11.Device D3DDev = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.DXGI.Device DXDev = D3DDev.QueryInterface<SharpDX.DXGI.Device>(); #if WINDOWS_PHONE_APP || !STORETOOLKIT SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D>(newSource); #else SharpDX.DXGI.ISurfaceImageSourceNative surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNative>(newSource); #endif SharpDX.Rectangle rt = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight); #if WINDOWS_PHONE_APP || !STORETOOLKIT SharpDX.Point pt; IntPtr obj; surfaceImageSourceNative.Device = TextShaping.Dev2D; surfaceImageSourceNative.BeginDraw(rt, new Guid("e8f7fe7a-191c-466d-ad95-975678bda998"), out obj, out pt); //d2d1_1.h SharpDX.Direct2D1.DeviceContext devcxt = SharpDX.ComObject.As<SharpDX.Direct2D1.DeviceContext>(obj); #else SharpDX.DrawingPoint pt; surfaceImageSourceNative.Device = TextShaping.DXDev; SharpDX.DXGI.Surface surf = surfaceImageSourceNative.BeginDraw(rt, out pt); SharpDX.Direct2D1.DeviceContext devcxt = new SharpDX.Direct2D1.DeviceContext(surf); //SharpDX.Direct2D1.Bitmap1 bmp = new SharpDX.Direct2D1.Bitmap1(devcxt, surf, new SharpDX.Direct2D1.BitmapProperties1() { DpiX = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiX, DpiY = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiY, PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), BitmapOptions = SharpDX.Direct2D1.BitmapOptions.CannotDraw | SharpDX.Direct2D1.BitmapOptions.Target }); //devcxt.Target = bmp; devcxt.BeginDraw(); #endif devcxt.Clear(new SharpDX.Color4(Windows.UI.Colors.White.R / 255.0f, Windows.UI.Colors.White.G / 255.0f, Windows.UI.Colors.White.B / 255.0f, Windows.UI.Colors.Transparent.A / 255.0f)); SharpDX.Direct2D1.Layer lyr = new SharpDX.Direct2D1.Layer(devcxt); //SharpDX.RectangleF.Infinite devcxt.PushLayer(new SharpDX.Direct2D1.LayerParameters1(new SharpDX.RectangleF(float.NegativeInfinity, float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity), null, SharpDX.Direct2D1.AntialiasMode.PerPrimitive, SharpDX.Matrix3x2.Identity, 1.0f, null, SharpDX.Direct2D1.LayerOptions1.None), lyr); devcxt.PushAxisAlignedClip(new SharpDX.RectangleF(pt.X, pt.Y, pt.X + pixelWidth, pt.Y + pixelHeight), SharpDX.Direct2D1.AntialiasMode.PerPrimitive); devcxt.Transform = SharpDX.Matrix3x2.Translation(pt.X, pt.Y); SharpDX.DirectWrite.GlyphRun gr = new SharpDX.DirectWrite.GlyphRun(); gr.FontFace = TextShaping.DWFontFace; gr.FontSize = (float)TopLevelFontSize; gr.BidiLevel = -1; int curlen = 0; for (int ct = 0; ct < Item.ItemRuns.Count(); ct++) { int newlen = curlen + Item.ItemRuns[ct].ItemText.Length; gr.Indices = Item.indices.Skip(Item.clusters[curlen]).TakeWhile((indice, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); gr.Offsets = Item.offsets.Skip(Item.clusters[curlen]).TakeWhile((offset, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); gr.Advances = Item.advances.Skip(Item.clusters[curlen]).TakeWhile((advance, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); if (Item.ItemRuns[ct].ItemText[0] == XMLRender.ArabicData.ArabicEndOfAyah) gr.Advances[0] = 0; SharpDX.Direct2D1.SolidColorBrush brsh = new SharpDX.Direct2D1.SolidColorBrush(devcxt, new SharpDX.Color4(XMLRender.Utility.ColorR(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorG(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorB(Item.ItemRuns[ct].Clr) / 255.0f, 0xFF / 255.0f)); devcxt.DrawGlyphRun(new SharpDX.Vector2((float) pt.X + (float)pixelWidth + Item.offsets[0].AdvanceOffset - (Item.clusters[curlen] == 0 ? 0 : Item.advances.Take(Item.clusters[curlen]).Sum()), Item.BaseLine), gr, brsh, SharpDX.Direct2D1.MeasuringMode.Natural); brsh.Dispose(); curlen = newlen; } devcxt.Transform = SharpDX.Matrix3x2.Identity; devcxt.PopAxisAlignedClip(); devcxt.PopLayer(); #if WINDOWS_PHONE_APP || !STORETOOLKIT gr.Dispose(); #else gr.FontFace = null; #endif #if WINDOWS_PHONE_APP || !STORETOOLKIT #else devcxt.EndDraw(); devcxt.Target = null; //bmp.Dispose(); #endif devcxt.Dispose(); #if WINDOWS_PHONE_APP || !STORETOOLKIT #else surf.Dispose(); #endif surfaceImageSourceNative.EndDraw(); surfaceImageSourceNative.Device = null; surfaceImageSourceNative.Dispose(); //DXDev.Dispose(); //D3DDev.Dispose(); return newSource; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect simple pilot sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface <SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var textFormat = new SharpDX.DirectWrite.TextFormat(device.DWriteFactory, "Arial", 16.0f); var blackBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.Black); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); bool doQuit = false; KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); DynamicColorRGBATextureProcessor colorProcessor = new DynamicColorRGBATextureProcessor(provider, device); KinectPilotProcessor pilot = KinectPilotProcessor.Default; KinectSensorBodyFrameProvider bodyFrameProvider = new KinectSensorBodyFrameProvider(sensor); bodyFrameProvider.FrameReceived += (sender, args) => { var body = args.FrameData.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { pilot.Process(body.GetJointTable()); } }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } colorProcessor.Update(context); context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorProcessor.Texture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); context2d.BeginDraw(); var rect = new SharpDX.RectangleF(0, 0, 200, 130); context2d.FillRectangle(rect, blackBrush); context2d.DrawText("Elevation: " + pilot.Elevation, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Y: " + pilot.SteeringY, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Z: " + pilot.SterringZ, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Push: " + pilot.Push, textFormat, rect, whiteBrush); context2d.EndDraw(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorProcessor.Dispose(); provider.Dispose(); sensor.Close(); }
public override void DrawLines(Pen pen, PointF[] points) { var brush = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, pen.Color.ToColor4()); var strokeStyle = pen.ToStrokeStyle(_renderTarget.Factory); var strokeWidth = StrokeWidthFromPen(pen); for (int i = 1; i < points.Length; i++) { _renderTarget.DrawLine( new SharpDX.Vector2(points[i - 1].X, points[i - 1].Y), new SharpDX.Vector2(points[i].X, points[i].Y), brush, strokeWidth, strokeStyle); } }
void InitText(SwapChain3 tempSwapChain) { init = true; device = tempSwapChain.GetDevice <SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); var texture2d = tempSwapChain.GetBackBuffer <Texture2D>(0); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); SharpDX.Direct2D1.BitmapProperties1 properties = new SharpDX.Direct2D1.BitmapProperties1( new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw); Surface backBuffer = tempSwapChain.GetBackBuffer <Surface>(0); d2dTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, new Size2(800, 600), properties); solidBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Coral); // Create a linear gradient brush. // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to, // NOT the geometry we will apply the brush. linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(d2dContext, new SharpDX.Direct2D1.LinearGradientBrushProperties() { StartPoint = new Vector2(50, 0), EndPoint = new Vector2(450, 0), }, new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[] { new SharpDX.Direct2D1.GradientStop() { Color = Color.Blue, Position = 0, }, new SharpDX.Direct2D1.GradientStop() { Color = Color.Green, Position = 1, } })); SharpDX.Direct2D1.RadialGradientBrushProperties rgb = new SharpDX.Direct2D1.RadialGradientBrushProperties() { Center = new Vector2(250, 525), RadiusX = 100, RadiusY = 100, }; // Create a radial gradient brush. // The center is specified in absolute coordinates, too. radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(d2dContext, ref rgb , new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[] { new SharpDX.Direct2D1.GradientStop() { Color = Color.Yellow, Position = 0, }, new SharpDX.Direct2D1.GradientStop() { Color = Color.Red, Position = 1, } })); }
private void LoadPipeline(RenderForm form) { int width = form.ClientSize.Width; int height = form.ClientSize.Height; viewport.Width = width; viewport.Height = height; viewport.MaxDepth = 1.0f; scissorRect.Right = width; scissorRect.Bottom = height; #if DEBUG // Enable the D3D12 debug layer. { DebugInterface.Get().EnableDebugLayer(); } #endif device = new Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_0); using (var factory = new Factory4()) { // Describe and create the command queue. CommandQueueDescription queueDesc = new CommandQueueDescription(CommandListType.Direct); commandQueue = device.CreateCommandQueue(queueDesc); // Describe and create the swap chain. SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = FrameCount, ModeDescription = new ModeDescription(width, height, new Rational(60, 1), Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, OutputHandle = form.Handle, //Flags = SwapChainFlags.None, SampleDescription = new SampleDescription(1, 0), IsWindowed = true }; SwapChain tempSwapChain = new SwapChain(factory, commandQueue, swapChainDesc); swapChain = tempSwapChain.QueryInterface<SwapChain3>(); tempSwapChain.Dispose(); frameIndex = swapChain.CurrentBackBufferIndex; } // Create descriptor heaps. // Describe and create a render target view (RTV) descriptor heap. DescriptorHeapDescription rtvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = FrameCount, Flags = DescriptorHeapFlags.None, Type = DescriptorHeapType.RenderTargetView }; renderTargetViewHeap = device.CreateDescriptorHeap(rtvHeapDesc); rtvDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); //Init Direct3D11 device from Direct3D12 device device11 = SharpDX.Direct3D11.Device.CreateFromDirect3D12(device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue); deviceContext11 = device11.ImmediateContext; device11on12 = device11.QueryInterface<SharpDX.Direct3D11.ID3D11On12Device>(); var d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded); // Create frame resources. CpuDescriptorHandle rtvHandle = renderTargetViewHeap.CPUDescriptorHandleForHeapStart; for (int n = 0; n < FrameCount; n++) { renderTargets[n] = swapChain.GetBackBuffer<Resource>(n); device.CreateRenderTargetView(renderTargets[n], null, rtvHandle); rtvHandle += rtvDescriptorSize; //init Direct2D surfaces SharpDX.Direct3D11.D3D11ResourceFlags format = new SharpDX.Direct3D11.D3D11ResourceFlags() { BindFlags = (int)SharpDX.Direct3D11.BindFlags.RenderTarget, CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None }; device11on12.CreateWrappedResource( renderTargets[n], format, (int)ResourceStates.Present, (int)ResourceStates.RenderTarget, typeof(SharpDX.Direct3D11.Resource).GUID, out wrappedBackBuffers[n]); //Init direct2D surface var d2dSurface = wrappedBackBuffers[n].QueryInterface<Surface>(); direct2DRenderTarget[n] = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied))); d2dSurface.Dispose(); } commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); d2dFactory.Dispose(); //Init font var directWriteFactory = new SharpDX.DirectWrite.Factory(); textFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Arial", SharpDX.DirectWrite.FontWeight.Bold, SharpDX.DirectWrite.FontStyle.Normal, 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near }; textBrush = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget[0], Color.White); directWriteFactory.Dispose(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect simple pilot sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface<SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var textFormat = new SharpDX.DirectWrite.TextFormat(device.DWriteFactory, "Arial", 16.0f); var blackBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.Black); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); bool doQuit = false; KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); DynamicColorRGBATextureProcessor colorProcessor = new DynamicColorRGBATextureProcessor(provider, device); KinectPilotProcessor pilot = KinectPilotProcessor.Default; KinectSensorBodyFrameProvider bodyFrameProvider = new KinectSensorBodyFrameProvider(sensor); bodyFrameProvider.FrameReceived += (sender, args) => { var body = args.FrameData.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { pilot.Process(body.GetJointTable()); } }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } colorProcessor.Update(context); context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorProcessor.Texture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); context2d.BeginDraw(); var rect = new SharpDX.RectangleF(0, 0, 200, 130); context2d.FillRectangle(rect, blackBrush); context2d.DrawText("Elevation: " + pilot.Elevation, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Y: " + pilot.SteeringY, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Z: " + pilot.SterringZ, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Push: " + pilot.Push, textFormat, rect, whiteBrush); context2d.EndDraw(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorProcessor.Dispose(); provider.Dispose(); sensor.Close(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect color sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface<SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); KinectBody[] bodyFrame = null; KinectSensorBodyFrameProvider bodyProvider = new KinectSensorBodyFrameProvider(sensor); bool doQuit = false; bool doUpload = false; ColorRGBAFrameData currentData = null; DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device); KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); provider.FrameReceived += (sender, args) => { currentData = args.FrameData; doUpload = true; }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; FaceFrameResult frameResult = null; SingleFaceProcessor faceProcessor = new SingleFaceProcessor(sensor); faceProcessor.FaceResultAcquired += (sender, args) => { frameResult = args.FrameResult; }; Func<PointF, Vector2> map = new Func<PointF, Vector2>((p) => { float x = p.X / 1920.0f * (float)swapChain.Width; float y = p.Y / 1080.0f * (float)swapChain.Height; return new Vector2(x,y); }); Func<float,float, Vector2> mapxy = new Func<float,float, Vector2>((px,py) => { float x = px / 1920.0f * (float)swapChain.Width; float y = py / 1080.0f * (float)swapChain.Height; return new Vector2(x,y); }); bodyProvider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; var body = bodyFrame.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { faceProcessor.AssignBody(body); } else { faceProcessor.Suspend(); } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } if (doUpload) { colorTexture.Copy(context, currentData); } context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorTexture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); if (frameResult != null) { context2d.BeginDraw(); var colorBound = frameResult.FaceBoundingBoxInColorSpace; RectangleF rect = new RectangleF(); Vector2 topLeft = mapxy(colorBound.Left, colorBound.Top); Vector2 bottomRight = mapxy(colorBound.Right, colorBound.Bottom); rect.Top = topLeft.Y; rect.Bottom = bottomRight.Y; rect.Left = topLeft.X; rect.Right = bottomRight.X; context2d.DrawRectangle(rect, whiteBrush, 3.0f); foreach (PointF point in frameResult.FacePointsInColorSpace.Values) { var ellipse = new SharpDX.Direct2D1.Ellipse() { Point = map(point), RadiusX = 5, RadiusY = 5 }; context2d.FillEllipse(ellipse, whiteBrush); } context2d.EndDraw(); } swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorTexture.Dispose(); provider.Dispose(); bodyProvider.Dispose(); faceProcessor.Dispose(); whiteBrush.Dispose(); context2d.Dispose(); sensor.Close(); }