Esempio n. 1
0
 public SharpDXDrawing(SharpDXDevice device)
     : base(device)
 {
     this.device = device;
     solidColorBrush = new SolidColorBrush(device.RenderTarget, Colors.Black);
     device.RenderTarget.Transform = Matrix3x2.Identity;
 }
Esempio n. 2
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
 
            // Direct2D
            var renderTargetProperties = new RenderTargetProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            var hwndRenderTargetProperties = new HwndRenderTargetProperties()
            {
                Hwnd = this.Handle,
                PixelSize = new Size2(bounds.Width, bounds.Height),
                PresentOptions = PresentOptions.Immediately,
            };
            renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);

            var bitmapProperties = new BitmapProperties()
            {
                PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore)
            };
            bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bounds.Width, bounds.Height), bitmapProperties);

            textFormat = new TextFormat(directWriteFacrtory, "Arial", FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 96.0f);
            textFormat.ParagraphAlignment = ParagraphAlignment.Center;
            textFormat.TextAlignment = TextAlignment.Center;

            solidColorBrush = new SolidColorBrush(renderTarget, Color4.White);
        }
Esempio n. 3
0
 void disposeBrush()
 {
     if (_brush_ == null)
         return;
     _brush_.Dispose();
     _brush_ = null;
 }
 public LineMarker(D2D.RenderTarget render, D2D.SolidColorBrush brush, D2D.StrokeStyle stroke, float thickness)
 {
     this.brush     = brush;
     this.stroke    = stroke;
     this.thickness = thickness;
     this.render    = render;
 }
        /// <summary>
        /// Gets the brush for the given device.
        /// </summary>
        /// <param name="engineDevice">The device for which to get the brush.</param>
        internal override D2D.Brush GetBrush(EngineDevice engineDevice)
        {
            // Check for disposed state
            if (base.IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            D2D.SolidColorBrush result = m_loadedBrushes[engineDevice.DeviceIndex];
            if (result == null)
            {
                // Load the brush
                result = new D2D.SolidColorBrush(
                    engineDevice.FakeRenderTarget2D,
                    m_singleColor.ToDXColor(),
                    new D2D.BrushProperties()
                {
                    Opacity   = m_opacity,
                    Transform = Matrix3x2.Identity.ToDXMatrix()
                });
                m_loadedBrushes[engineDevice.DeviceIndex] = result;
            }

            return(result);
        }
            /// <summary>
            /// Called when [render].
            /// </summary>
            /// <param name="context">The context.</param>
            protected override void OnRender(RenderContext2D context)
            {
                if (background == null)
                {
                    Background = new D2D.SolidColorBrush(context.DeviceContext, new Color4(0.8f, 0.8f, 0.8f, 0.6f));
                }
                if (foreground == null)
                {
                    Foreground = new D2D.SolidColorBrush(context.DeviceContext, Color.Blue);
                }
                var str = statistics.GetDetailString();

                if (str != previousStr)
                {
                    previousStr = str;
                    RemoveAndDispose(ref textLayout);
                    textLayout = Collect(new TextLayout(factory, str, format, float.MaxValue, float.MaxValue));
                }
                var metrices = textLayout.Metrics;

                renderBound.Width  = Math.Max(metrices.Width, renderBound.Width);
                renderBound.Height = metrices.Height;
                context.DeviceContext.Transform = Matrix3x2.Translation((float)context.ActualWidth - renderBound.Width, 0);
                context.DeviceContext.FillRectangle(renderBound, background);
                context.DeviceContext.DrawTextLayout(Vector2.Zero, textLayout, foreground);
            }
Esempio n. 7
0
        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
        {
            SharpDX.Vector2 startPoint;
            SharpDX.Vector2 endPoint;

            float start      = ChartPanel.X;
            float halfHeight = ChartPanel.H / 2;

            Print("Start Point " + start + " height " + ChartPanel.H + " half height " + halfHeight);

            if (!IsInHitTest)
            {
                SharpDX.Direct2D1.Brush areaBrushDx;
                areaBrushDx = areaBrush.ToDxBrush(RenderTarget);
                SharpDX.Direct2D1.SolidColorBrush customDXBrush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget,
                                                                                                        SharpDX.Color.DodgerBlue);

                for (int index = 0; index < 5; index++)
                {
                    int spacer = index * 20;
                    startPoint = new SharpDX.Vector2(start, halfHeight + spacer);
                    endPoint   = new SharpDX.Vector2(ChartPanel.X + ChartPanel.W, halfHeight + spacer);
                    drawRow(startPoint: startPoint, endPoint: endPoint, areaBrushDx: areaBrushDx);
                }

                areaBrushDx.Dispose();
            }
        }
Esempio n. 8
0
        private void CursorData(float x, float y)
        {
            if (canvasparam.showcursordata == ShowCursorData.Hide)
            {
                return;
            }
            string value = "时间:";
            float  time  = 0F;

            if (dlList.Count > 0)
            {
                var c = listAxisParam.Find(t => t.Attributes == "Time");
                time = (x - canvasparam.OriginX) < 0 ? 0 : (x - canvasparam.OriginX) / (dlList[0].Hlength / (c.MaxScale - c.MinScale));
            }
            value += time.ToString("f2") + "\r\n";
            for (int i = 0; i < dlList.Count; i++)
            {
                value += dlList[i].Caption + ":" + dlList[i].GetLineData(x, y) + "\r\n";
            }
            var        brush  = new SharpDX.Direct2D1.SolidColorBrush(_renderTarget, new RawColor4(0, 0, 1, 1));
            RawVector2 pointS = new RawVector2(x, canvasparam.OriginY);
            RawVector2 pointE = new RawVector2(x, canvasparam.OriginY - canvasparam.VerticalLength);

            _renderTarget.DrawLine(pointS, pointE, brush);
            _renderTarget.DrawText(value, new TextFormat(dwfactory, "Arial", 12), new RawRectangleF(x, y, x + 100, y + 100), brush);
        }
Esempio n. 9
0
        public static void WatermarkText(Stream imageStream, Stream outputStream, string watermark, string font = "Times New Roman", float fontSize = 30.0f, int colorARGB = TransparentWhite)
        {
            using (var wic = new WIC.ImagingFactory2())
                using (var d2d = new D2D.Factory())
                    using (var image = CreateWicImage(wic, imageStream))
                        using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
                            using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
                                using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image))
                                    using (var dwriteFactory = new DWrite.Factory())
                                        using (var brush = new D2D.SolidColorBrush(target, new Color(colorARGB)))
                                        {
                                            target.BeginDraw();
                                            {
                                                target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear);
                                                target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                                var textFormat = new DWrite.TextFormat(dwriteFactory, font, DWrite.FontWeight.Bold, DWrite.FontStyle.Normal, fontSize)
                                                {
                                                    ParagraphAlignment = DWrite.ParagraphAlignment.Far,
                                                    TextAlignment      = DWrite.TextAlignment.Trailing,
                                                };
                                                target.DrawText(watermark, textFormat, new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
                                            }
                                            target.EndDraw();

                                            SaveD2DBitmap(wic, wicBitmap, outputStream);
                                        }
        }
Esempio n. 10
0
 public DrawingContext(Direct2D.RenderTarget g)
 {
     this.D2DTarget = g;
     StrokeBrush    = new Direct2D.SolidColorBrush(g, Color.Black);
     SolidBrush     = new Direct2D.SolidColorBrush(g, Color.White);
     MarkerBrush    = new Direct2D.SolidColorBrush(g, Color.White);
 }
Esempio n. 11
0
        public InfoText(SharpDX.Direct3D11.Device device, int width, int height)
        {
            _immediateContext = device.ImmediateContext;
            _rect.Size = new Size2F(width, height);
            _bitmapSize = width * height * 4;
            IsEnabled = true;

            using (var factoryWic = new SharpDX.WIC.ImagingFactory())
            {
                _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic,
                    width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad);
            }

            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None,
                    SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT);

            using (var factory2D = new SharpDX.Direct2D1.Factory())
            {
                _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties);
                _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default;
            }

            using (var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared))
            {
                _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20);
            }

            Color4 color = new Color4(1, 1, 1, 1);
            _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color);
            _clearColor = color;
            _clearColor.Alpha = 0;

            _renderTexture = new Texture2D(device, new Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.Write,
                Format = Format.R8G8B8A8_UNorm,
                Height = height,
                Width = width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Dynamic
            });

            OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription()
            {
                Format = _renderTexture.Description.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels = 1,
                    MostDetailedMip = 0
                }
            });
        }
Esempio n. 12
0
 //public static Brush TEXT_BRUSH;
 public static void Initialize(RenderTarget g)
 {
     SCBRUSH_RED = new SolidColorBrush(g, Color.Red);
     SCBRUSH_BLACK = new SolidColorBrush(g, Color.Black);
     WRITE_FACTORY = new SharpDX.DirectWrite.Factory();
     TEXT_FORMAT = new TextFormat(WRITE_FACTORY, "Arial", 14);
     //TEXT_BRUSH = new SolidColorBrush(g, Color.Red);
 }
Esempio n. 13
0
 void TextWriter_ChangeRenderTarget(RenderTarget newRenderTarget)
 {
     //throw new NotImplementedException();
     renderTarget = device.renderTarget;
     brush = new SharpDX.Direct2D1.SolidColorBrush(renderTarget, xPFT.DrawingBase.Convertor.ColorConvertor(curentColor, opacity));
     SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory();
     textFormat = new SharpDX.DirectWrite.TextFormat(factory, FontName, FontSize);
 }
        public void DrawMarkerEffect(MyTextLayout layout, HilightType type, int start, int length, double x, double y, bool isBold, Color4?effectColor = null)
        {
            if (type == HilightType.None)
            {
                return;
            }

            float thickness = isBold ? BoldThickness : NormalThickness;

            Color4 color;

            if (effectColor != null)
            {
                color = (Color4)effectColor;
            }
            else if (type == HilightType.Select)
            {
                color = this.Hilight;
            }
            else
            {
                color = this.Foreground;
            }

            IMarkerEffecter effecter = null;

            D2D.SolidColorBrush brush = this._factory.GetSolidColorBrush(color);

            if (type == HilightType.Squiggle)
            {
                effecter = new D2DSquilleLineMarker(this.render, brush, this._factory.GetStroke(HilightType.Squiggle), thickness);
            }
            else if (type == HilightType.Select)
            {
                effecter = new HilightMarker(this.render, brush);
            }
            else if (type == HilightType.None)
            {
                effecter = null;
            }
            else
            {
                effecter = new LineMarker(this.render, brush, this._factory.GetStroke(type), thickness);
            }

            if (effecter != null)
            {
                bool isUnderline = type != HilightType.Select;

                DW.HitTestMetrics[] metrics = layout.HitTestTextRange(start, length, (float)x, (float)y);
                foreach (DW.HitTestMetrics metric in metrics)
                {
                    float offset = isUnderline ? metric.Height : 0;
                    effecter.Draw(metric.Left, metric.Top + offset, metric.Width, metric.Height);
                }
            }
        }
Esempio n. 15
0
        private void DrawDataLine(RawVector2[] pfdata)
        {
            var brush = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, color);

            for (int i = 0; i < pfdata.Length - 1; i++)
            {
                cp._renderTarget.DrawLine(pfdata[i], pfdata[i + 1], brush, lineWith);
            }
        }
Esempio n. 16
0
 public SolidColorBrush(D2D.RenderTarget target, Color color)
 {
     if (target != null)
     {
         d2dBrush = new D2D.SolidColorBrush(target, color.ToD2D());
     }
     else
         throw new ArgumentNullException();
 }
Esempio n. 17
0
 internal void InitializeResources(RenderTarget d2dRenderTarget)
 {
     if (!initialized)
     {
         Fill = new SolidColorBrush(d2dRenderTarget, Colors.Green);
         Stroke = new SolidColorBrush(d2dRenderTarget, Colors.Azure);
         initialized = true;
        texture = MainGame.LoadFromFile(d2dRenderTarget, @"C:\git\KinectLight\resources\Logo_EDGE_40.bmp");
     }
 }
Esempio n. 18
0
 /// <summary>
 /// Draws the outline of a rectangle.
 /// </summary>
 /// <param name="pen">The pen.</param>
 /// <param name="rect">The rectangle bounds.</param>
 public void DrawRectange(Pen pen, Rect rect)
 {
     using (SharpDX.Direct2D1.SolidColorBrush brush = this.Convert(pen.Brush))
     {
         this.renderTarget.DrawRectangle(
             this.Convert(rect),
             brush,
             (float)pen.Thickness);
     }
 }
Esempio n. 19
0
 /// <summary>
 /// Draws a line.
 /// </summary>
 /// <param name="pen">The stroke pen.</param>
 /// <param name="p1">The first point of the line.</param>
 /// <param name="p1">The second point of the line.</param>
 public void DrawLine(Pen pen, Perspex.Point p1, Perspex.Point p2)
 {
     if (pen != null)
     {
         using (SharpDX.Direct2D1.SolidColorBrush d2dBrush = this.Convert(pen.Brush))
         {
             this.renderTarget.DrawLine(p1.ToSharpDX(), p2.ToSharpDX(), d2dBrush);
         }
     }
 }
Esempio n. 20
0
 public SolidColorBrush(D2D.RenderTarget target, Color color)
 {
     if (target != null)
     {
         d2dBrush = new D2D.SolidColorBrush(target, color.ToD2D());
     }
     else
     {
         throw new ArgumentNullException();
     }
 }
Esempio n. 21
0
        public void Create3dObjects()
        {
            //Create RenderWindow
            RenderWindowInstance = new ModelRenderWindow();
            FormInstance = RenderWindowInstance.CreateWindow(1080,1240,FormStartPosition.CenterScreen);

            //Create SwapChain
            SwapChainCreator = new ModelSwapChainDesc();
            SwapChainD = SwapChainCreator.CreateSwapChain(2, Usage.RenderTargetOutput, FormInstance.Handle, true, 0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm, 1,0,SwapChainFlags.AllowModeSwitch, SwapEffect.Discard);

            //Create Device
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SwapChainD, out GraphicsDevice, out NewSwapChain);

            //Create Back buffer
            BackBuffer = Surface.FromSwapChain(NewSwapChain, 0);

            //Create Factory
            FactoryD2D FactoryInstance = new FactoryD2D();

            //Create RenderTarget
            RenderTargetInstance = new ModelRenderTarget();
            RenderTarget = RenderTargetInstance.CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore), RenderTargetType.Default, RenderTargetUsage.None, BackBuffer, FactoryInstance);

            RenderLoop.Run(FormInstance, () =>
            {

                RenderTarget.BeginDraw();
                RenderTarget.Transform = Matrix3x2.Identity;
                RenderTarget.Clear(Color.White);

                using (var brush = new SolidColorBrush(RenderTarget, Color.Red))
                {
                    //for (int x = 0; x < RenderTarget.Size.Width; x += 10)
                    //    RenderTarget.DrawLine(new Vector2(x, 0), new Vector2(x, RenderTarget.Size.Height), brush, 0.5f);

                    //for (int y = 0; y < RenderTarget.Size.Height; y += 10)
                    //    RenderTarget.DrawLine(new Vector2(0, y), new Vector2(RenderTarget.Size.Width, y), brush, 0.5f);
                    RenderTarget.DrawLine(new Vector2(300, 10), new Vector2(300, 300), brush,1.5f);
                   // RenderTarget.FillRectangle(new RectangleF(RenderTarget.Size.Width / 2 - 50, RenderTarget.Size.Height / 2 - 50, 100, 100), brush);
                }

              //  RenderTarget.DrawRectangle(
                   // new RectangleF(RenderTarget.Size.Width / 2 - 100, RenderTarget.Size.Height / 2 - 100, 200, 200),
                   // new SolidColorBrush(RenderTarget, Color.CornflowerBlue));

                RenderTarget.EndDraw();

                NewSwapChain.Present(0, PresentFlags.None);
            });

            RenderTarget.Dispose();
            NewSwapChain.Dispose();
            GraphicsDevice.Dispose();
        }
Esempio n. 22
0
 /* CONSTRUCTOR METHOD */
 /// <summary>
 /// Constructs a 2D block of text that can displayed in a 3D rendering window.
 /// </summary>
 /// <param name="window">A reference to a Direct3D-capable rendering window.</param>
 public TextDX(Window3D window)
     : base(window)
 {
     ColorBrush		= Tag(new SolidColorBrush(RenderTarget, Color4.Black));
     Font			= "Calibri";
     Size			= 16f;
     Style			= FontStyle.Normal;
     Text			= string.Empty;
     UpdateSettings	= true;
     Weight			= FontWeight.Normal;
 }
Esempio n. 23
0
 public SharpDXDrawing(SharpDXDevice device, Window window)
     : base(device)
 {
     this.device = device;
     brush = new SolidColorBrush(device.RenderTarget, new Color4(lastColor.PackedRgba));
     device.RenderTarget.Transform = Matrix3x2.Identity;
     drawShader = new SharpDXDrawShader(device);
     Reset(window.ViewportPixelSize);
     window.ViewportSizeChanged += Reset;
     device.Context.OutputMerger.BlendState = device.GetAlphaBlendStateLazy();
 }
Esempio n. 24
0
        private void InitFont()
        {
            var directWriteFactory = new SharpDX.DirectWrite.Factory();

            _directWriteTextFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, _fontName, _fontSize)
            {
                TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near
            };
            _directWriteFontColor = new SharpDX.Direct2D1.SolidColorBrush(_direct2DRenderTarget, _fontColor);
            directWriteFactory.Dispose();
        }
Esempio n. 25
0
 public void InitializeDevice(IntPtr windowHandle)
 {
     D3Device = DirectXTools.CreateD3Device();
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForHwnd(D3Device, windowHandle);
         DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Esempio n. 26
0
 public void InitializeDevice(ComObject coreWindow)
 {
     D3Device = DirectXTools.CreateD3Device();
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForCoreWindow(D3Device, coreWindow);
         DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Esempio n. 27
0
 /* CONSTRUCTOR & DESTRUCTOR METHODS */
 /// <summary>
 /// Constructs a generic 2D rectangular panel that will be displayed as a flat, image-like rendering in the 3D rendering window.
 /// </summary>
 /// <param name="window">A reference to a Direct3D-capable rendering window in which this entity will be displayed.</param>
 protected Panel(Window3D window)
     : base(window)
 {
     BackgroundBrush = Tag(new SolidColorBrush(RenderTarget, Color.SlateGray));
     BorderBrush = Tag(new SolidColorBrush(RenderTarget, Color.SlateGray));
     Rectangle = new RoundedRectangle()
     {
         RadiusX = 0f,
         RadiusY = 0f,
         Rect = new RectangleF(0, 0, 100, 100),
     };
 }
Esempio n. 28
0
        private void Update(bool forceUpdate = false)
        {
            if (isUpdated || forceUpdate)
            {
                isUpdated = false;

                strokeBrush?.Dispose();
                strokeBrush = new d2.SolidColorBrush(Renderer.Device, _stroke.ToColor4());

                strokeStyle?.Dispose();
                strokeStyle = new d2.StrokeStyle(Renderer.Factory, _strokeStyleProp);
            }
        }
Esempio n. 29
0
 /// <summary>
 /// Get brush using specified color.
 /// </summary>
 /// <param name="dc">Device context.</param>
 /// <param name="color">Color in int.</param>
 /// <returns>Created or cached brush.</returns>
 public D2D.SolidColorBrush GetBrush(D2D.DeviceContext dc, int color)
 {
     if (this.brushCache.TryGetValue(color, out var brush))
     {
         return(brush);
     }
     else
     {
         var newBrush = new D2D.SolidColorBrush(dc, Helpers.GetColor(color));
         this.brushCache.Add(color, newBrush);
         return(newBrush);
     }
 }
Esempio n. 30
0
 /// <summary>
 /// Draws a filled rectangle.
 /// </summary>
 /// <param name="brush">The brush.</param>
 /// <param name="rect">The rectangle bounds.</param>
 public void FillRectange(Perspex.Media.Brush brush, Rect rect)
 {
     using (SharpDX.Direct2D1.SolidColorBrush b = this.Convert(brush))
     {
         this.renderTarget.FillRectangle(
             new RectangleF(
                 (float)rect.X,
                 (float)rect.Y,
                 (float)rect.Width,
                 (float)rect.Height),
             b);
     }
 }
Esempio n. 31
0
 private SolidColorBrush(Color pColor, IGraphicsAdapter pTarget)
 {
     if (pTarget.Method == RenderMethods.DirectX)
     {
         var dx = (DirectXAdapter)pTarget;
         _brush         = new SharpDX.Direct2D1.SolidColorBrush(dx.Context, new SharpDX.Color4(pColor.R / 255f, pColor.G / 255f, pColor.B / 255f, pColor.A / 255f));
         _brush.Opacity = pColor.A / 255f;
     }
     else
     {
         throw new NotImplementedException();
     }
 }
        private void Update(bool updateForce = false)
        {
            if (isUpdated || updateForce)
            {
                isUpdated = false;

                tFormat?.Dispose();
                tFormat = CreateTextFormat(this.Font);

                foregroundBrush?.Dispose();
                foregroundBrush = new d2.SolidColorBrush(Renderer.Device, Foreground.ToColor4());
            }
        }
Esempio n. 33
0
 public void InitializeDeviceGdiCompatible(IntPtr windowHandle, int width, int height)
 {
     using (var d3device = DirectXTools.CreateD3Device())
     {
         RenderTarget = DirectXTools.CreateRenderTarget(Direct2DFactory, d3device);
         _solidBrush  = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
         SwapChain    = DirectXTools.CreateSwapChainForHwnd(d3device, windowHandle);
         //DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
         DirectXTools.CreateDeviceContextCPUBitmap(RenderTarget, width, height);
         Bitmaps.SetRenderTarget(RenderTarget);
         TextLayouts.SetRenderTarget(RenderTarget);
     }
 }
Esempio n. 34
0
        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();
        }
Esempio n. 35
0
        private void ResetBurshes(RenderContainer renderContainer)
        {
            _selectedColorBrush?.Dispose();
            _spacingColorBrush?.Dispose();
            _notMappedColorBrush?.Dispose();
            _gridColorBrush?.Dispose();

            RenderTarget target2D = renderContainer.BackBuffer.Target2D;

            _selectedColorBrush  = new SolidColorBrush(target2D, SelectedColor.ToColor4(), null);
            _spacingColorBrush   = new SolidColorBrush(target2D, SpacingColor.ToColor4(), null);
            _notMappedColorBrush = new SolidColorBrush(target2D, NotMappedColor.ToColor4(), null);
            _gridColorBrush      = new SolidColorBrush(target2D, GridColor.ToColor4(), null);
        }
Esempio n. 36
0
        private static void Main()
        {
            var wicFactory = new ImagingFactory();
            var d2dFactory = new SharpDX.Direct2D1.Factory();

            string filename = "output.jpg";
            const int width = 512;
            const int height = 512;

            var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128, height-128) });

            var wicBitmap = new Bitmap(wicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad);

            var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties);

            var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);

            d2dRenderTarget.BeginDraw();
            d2dRenderTarget.Clear(Color.Black);
            d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null);
            d2dRenderTarget.EndDraw();

            if (File.Exists(filename))
                File.Delete(filename);

            var stream = new WICStream(wicFactory, filename, NativeFileAccess.Write);
            // Initialize a Jpeg encoder with this stream
            var encoder = new JpegBitmapEncoder(wicFactory);
            encoder.Initialize(stream);

            // Create a Frame encoder
            var bitmapFrameEncode = new BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare;
            bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
            bitmapFrameEncode.WriteSource(wicBitmap);

            bitmapFrameEncode.Commit();
            encoder.Commit();

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();

            System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory,filename)));
        }
Esempio n. 37
0
        protected override void Initialize(DemoConfiguration demoConfiguration)
        {
            base.Initialize(demoConfiguration);
            Factory2D = new SharpDX.Direct2D1.Factory();
            using (var surface = BackBuffer.QueryInterface<Surface>())
            {
                RenderTarget2D = new RenderTarget(Factory2D, surface,
                                                  new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)));
            }
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;

            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            SceneColorBrush = new SolidColorBrush(RenderTarget2D, Color.White);
        }
Esempio n. 38
0
 /// <summary>
 /// Draws text.
 /// </summary>
 /// <param name="foreground">The foreground brush.</param>
 /// <param name="rect">The output rectangle.</param>
 /// <param name="text">The text.</param>
 public void DrawText(Perspex.Media.Brush foreground, Rect rect, FormattedText text)
 {
     if (!string.IsNullOrEmpty(text.Text))
     {
         using (SharpDX.Direct2D1.SolidColorBrush brush = this.Convert(foreground))
             using (SharpDX.DirectWrite.TextFormat format = TextService.GetTextFormat(this.directWriteFactory, text))
             {
                 this.renderTarget.DrawText(
                     text.Text,
                     format,
                     this.Convert(rect),
                     brush);
             }
     }
 }
        private void InitializeDevices()
        {
            try
            {
                SwapChainDescription                   = new DXGI.SwapChainDescription();
                SwapChainDescription.BufferCount       = 2;
                SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0);
                SwapChainDescription.SwapEffect        = DXGI.SwapEffect.Discard;
                SwapChainDescription.Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput;
                SwapChainDescription.IsWindowed        = true;
                SwapChainDescription.ModeDescription   = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm);
                SwapChainDescription.OutputHandle      = GameWindowHandle;

                D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain);

                DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>();
                factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll);

                D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>();

                Backbuffer       = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0);
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer);
                D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height);
                D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView);

                DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>();

                D2DFactory       = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded);
                D2DDevice        = new D2D1.Device(D2DFactory, DXGIDevice);
                D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);

                RenderTargetSurface        = Backbuffer.QueryInterface <DXGI.Surface>();
                RenderTarget               = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)));
                RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive;

                // Initialize debug drawings brushes
                DrawingBoundsBrush  = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f));
                CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f));

                RenderFrame = new RenderFrame(RenderTarget);

                Clock = Stopwatch.StartNew();
            }
            catch (Exception ex)
            {
                throw new DeviceInitializationException("Unable to initialize DirectX device!", ex);
            }
        }
Esempio n. 40
0
        private void InitializeDirectXResources()
        {
            var clientSize     = ClientSize;
            var backBufferDesc = new DXGI.ModeDescription(clientSize.Width, clientSize.Height,
                                                          new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm);

            var swapChainDesc = new DXGI.SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = Handle,
                SwapEffect        = DXGI.SwapEffect.Discard,
                IsWindowed        = false
            };

            D3D11.Device.CreateWithSwapChain(D3D.DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport,
                                             new[] { D3D.FeatureLevel.Level_10_0 }, swapChainDesc, out _d3DDevice, out var swapChain);
            _d3DDeviceContext = _d3DDevice.ImmediateContext;

            _swapChain = new DXGI.SwapChain1(swapChain.NativePointer);

            _d2DFactory = new D2D1.Factory();

            using (var backBuffer = _swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                _renderTargetView = new D3D11.RenderTargetView(_d3DDevice, backBuffer);
                _renderTarget     = new D2D1.RenderTarget(_d2DFactory, backBuffer.QueryInterface <DXGI.Surface>(),
                                                          new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)))
                {
                    TextAntialiasMode = D2D1.TextAntialiasMode.Cleartype
                };
            }

            _solidColorBrush = new D2D1.SolidColorBrush(_renderTarget, Color.White);

            _dwFactory  = new DW.Factory(DW.FactoryType.Shared);
            _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
            };

            _bitmap = _paradigm.Config.Gui.UseBitmap ? Properties.Resources.Einstein.ToD2D1Bitmap(_renderTarget) : null;
        }
        /// <summary>
        /// 描画
        /// </summary>
        public void Paint()
        {
            render.BeginDraw();

            render.Clear(background);

            //Value2Map();
            var fontFactory = new SharpDX.DirectWrite.Factory();
            var textFormat  = new TextFormat(fontFactory, "メイリオ", 24.0f);

            textFormat.TextAlignment = TextAlignment.Center;
            var textBrush = new SharpDX.Direct2D1.SolidColorBrush(render, new RawColor4(1f, 1f, 1f, 1f));

            render.DrawText("ここにカルノー図が表示されます", textFormat, new RawRectangleF(10, (this.height / 2) - 12, target.Width - 10, target.Height - 10), textBrush, DrawTextOptions.None);

            render.EndDraw();
        }
Esempio n. 42
0
        public void InitializeDevice(int width, int height, object swapChainPanel)
        {
            var nativePanel = ComObject.As <DXGI.ISwapChainPanelNative>(swapChainPanel);

            Debug.Assert(nativePanel != null, $"{nameof(swapChainPanel)} should not be null.");

            D3Device = DirectXTools.CreateD3Device();
            {
                RenderTarget          = DirectXTools.CreateRenderTarget(Direct2DFactory, D3Device);
                _solidBrush           = new Direct2D1.SolidColorBrush(RenderTarget, Color.Black);
                SwapChain             = DirectXTools.CreateSwapChain(width, height, D3Device);
                nativePanel.SwapChain = SwapChain;
                DirectXTools.CreateDeviceSwapChainBitmap(SwapChain, RenderTarget);
                Bitmaps.SetRenderTarget(RenderTarget);
                TextLayouts.SetRenderTarget(RenderTarget);
            }
        }
Esempio n. 43
0
        public override void Draw()
        {
            calculate();
            var strokeStyleProperties = new SharpDX.Direct2D1.StrokeStyleProperties();

            strokeStyleProperties.DashStyle = SharpDX.Direct2D1.DashStyle.Custom;
            float[] dashes = { 10, 5 };
            //strokeStyleProperties.DashCap = SharpDX.Direct2D1.CapStyle.Square;
            //strokeStyleProperties.DashOffset = 0.2F;
            var strokeStyle = new StrokeStyle(cp.factory, strokeStyleProperties, dashes);
            var brush       = new SharpDX.Direct2D1.SolidColorBrush(cp._renderTarget, new RawColor4(0.439F, 0.501F, 0.564F, 1));

            for (int i = 0; i < ScaleCount; i++)
            {
                cp._renderTarget.DrawLine(listpointS[i], listpointE[i], brush, 0.5F, strokeStyle);
            }
        }
        protected override void Initialize(DemoConfiguration demoConfiguration)
        {
            Factory2D = new SharpDX.Direct2D1.Factory();
            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            HwndRenderTargetProperties properties = new HwndRenderTargetProperties();
            properties.Hwnd = DisplayHandle;
            properties.PixelSize = new SharpDX.DrawingSize(demoConfiguration.Width, demoConfiguration.Height);
            properties.PresentOptions = PresentOptions.None;

            RenderTarget2D = new WindowRenderTarget(Factory2D, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)), properties);

            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;


            SceneColorBrush = new SolidColorBrush(RenderTarget2D, Color.White);
        }
Esempio n. 45
0
		private void InitializeGraphics()
		{
			factory = new Factory(FactoryType.SingleThreaded, DebugLevel.None);

			renderTargetProperties = new RenderTargetProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied));

			hwndRenderTargetProperties = new HwndRenderTargetProperties();
			hwndRenderTargetProperties.Hwnd = this.Handle;
			hwndRenderTargetProperties.PixelSize = new SharpDX.Size2(Width, Height);
			hwndRenderTargetProperties.PresentOptions = PresentOptions.None;

			windowRenderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties);

			backgroundColor = new RawColor4(BackColor.R, BackColor.G, BackColor.B, BackColor.A);

			borderColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0.5f, 0.5f, 0.5f, 1));
			wayColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0, 0, 1, 0.3f));
			currentPositionColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0, 0, 1, 1));

			graphicsInitialized = true;
		}
Esempio n. 46
0
        public Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, GlyphRun glyphRun, GlyphRunDescription glyphRunDescription, ComObject clientDrawingEffect)
        {
            var pathGeometry = new PathGeometry(_d2DFactory);
            var geometrySink = pathGeometry.Open();

            var fontFace = glyphRun.FontFace;
            if (glyphRun.Indices.Length > 0)
                fontFace.GetGlyphRunOutline(glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, glyphRun.BidiLevel % 2 != 0, geometrySink);
            geometrySink.Close();
            geometrySink.Dispose();
            fontFace.Dispose();

            var matrix = new Matrix3x2()
            {
                M11 = 1,
                M12 = 0,
                M21 = 0,
                M22 = 1,
                M31 = baselineOriginX,
                M32 = baselineOriginY
            };

            var transformedGeometry = new TransformedGeometry(_d2DFactory, pathGeometry, matrix);

            var  brushColor = (Color4)Color.Black;

            if (clientDrawingEffect != null && clientDrawingEffect is ColorDrawingEffect)
                brushColor = (clientDrawingEffect as ColorDrawingEffect).Color;

            var brush = new SolidColorBrush(_renderTarget, brushColor);
            
            _renderTarget.DrawGeometry(transformedGeometry, brush);
            _renderTarget.FillGeometry(transformedGeometry, brush);

            pathGeometry.Dispose();
            transformedGeometry.Dispose();
            brush.Dispose();

            return SharpDX.Result.Ok;
        }
        /// <summary>
        /// Gets a brush for the specified render target and color.
        /// </summary>
        /// <param name="renderTarget">The render target.</param>
        /// <param name="color">The color.</param>
        /// <returns>The brush (either from the cache or newly created).</returns>
        /// <remarks>
        /// Brushes are cached because their creation is expensive.
        /// </remarks>
        private Brush GetBrush(RenderTarget renderTarget, Color color)
        {
            Brush brush;

            lock (this.brushes)
            {
                if (!this.brushes.TryGetValue(color, out brush))
                {
                    brush = new SolidColorBrush(renderTarget, color);
                    this.brushes[color] = brush;
                }
            }

            return brush;
        }
Esempio n. 48
0
 /// <summary>
 /// Initializes a new DirectXPen class.
 /// </summary>
 public DirectXPen()
 {
     _colorBrush = new SolidColorBrush(DirectXHelper.RenderTarget, SharpDX.Color.Black);
     Color = Color.Black;
     Width = 1;
 }
Esempio n. 49
0
 /// <summary>
 /// Initializes a new DirectXPen class.
 /// </summary>
 /// <param name="color">The Color.</param>
 /// <param name="width">The Width.</param>
 public DirectXPen(Color color, float width)
 {
     _colorBrush = new SolidColorBrush(DirectXHelper.RenderTarget, DirectXHelper.ConvertColor(color));
     Width = width;
 }
Esempio n. 50
0
        public virtual void Update(DeviceContext context, TargetBase target, DeviceManager deviceManager, Point screenSize, float dt, float elapsedTime)
        {
            context.DrawRectangle(screenSize.ApplyTo(GamesParams.Margin0.ToRectangleWith(GamesParams.Margin1)), GamesParams.ObstaclesColor, 2);

            _gameTime += dt;

            if (!_gameManager.IsTraining)
            {
                const float u = 1.00f;
                if (_gameTime < u && !AfterStartFreeze)
                {
                    var op = 1 - _gameTime / u;
                    var hideBrush = new SolidColorBrush(deviceManager.ContextDirect2D, Colors.White,
                                                        new BrushProperties { Opacity = op });
                    context.FillRectangle(screenSize.ApplyTo(new RectangleF(0, 0, 1, 1)), hideBrush);
                }
                else
                {
                    AfterStartFreeze = true;
                }

                if (_gameTime > _gameMaxTime - u)
                {
                    var op = 1 - (_gameMaxTime - _gameTime) / u;
                    var hideBrush = new SolidColorBrush(deviceManager.ContextDirect2D, Colors.White,
                                                        new BrushProperties { Opacity = op });
                    context.FillRectangle(screenSize.ApplyTo(new RectangleF(0, 0, 1, 1)), hideBrush);
                }

                float bar;
                bar = _gameManager.IsTraining ? 1 : _gameTime / _gameMaxTime;
                _gameManager.Page.SetTimeRectangleWidth(bar);
                _gameManager.RedrawPointsAndLifes();

                if (_gameTime > _gameMaxTime)
                    _gameManager.Win(100);
            }
        }
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Query the default device for the supported device and context interfaces.
            device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>();

            // Query for the adapter and more advanced DXGI objects.
            SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>();

            // Description for our swap chain settings.
            SwapChainDescription1 description = new SwapChainDescription1()
            {
                // 0 means to use automatic buffer sizing.
                Width = 0,
                Height = 0,
                // 32 bit RGBA color.
                Format = Format.B8G8R8A8_UNorm,
                // No stereo (3D) display.
                Stereo = false,
                // No multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // Use the swap chain as a render target.
                Usage = Usage.RenderTargetOutput,
                // Enable double buffering to prevent flickering.
                BufferCount = 2,
                // No scaling.
                Scaling = Scaling.None,
                // Flip between both buffers.
                SwapEffect = SwapEffect.FlipSequential,
            };

            // Generate a swap chain for our window based on the specified description.
            swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null);

            // Get the default Direct2D device and create a context.
            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            // Specify the properties for the bitmap that we will use as the target of our Direct2D operations.
            // We want a 32-bit BGRA surface with premultiplied alpha.
            BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw);

            // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target.
            Surface backBuffer = swapChain.GetBackBuffer<Surface>(0);
            d2dTarget = new Bitmap1(d2dContext, backBuffer, properties);

            // Create a solid color brush.
            solidBrush = new 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 LinearGradientBrush(d2dContext, new LinearGradientBrushProperties()
                {
                    StartPoint = new Vector2(50, 0),
                    EndPoint = new Vector2(450, 0),
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                    {
                        new GradientStop()
                        {
                            Color = Color.Blue,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Green,
                            Position = 1,
                        }
                    }));

            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties()
                {
                    Center = new Vector2(250, 525),
                    RadiusX = 100,
                    RadiusY = 100,
                },
                new GradientStopCollection(d2dContext, new GradientStop[]
                {
                        new GradientStop()
                        {
                            Color = Color.Yellow,
                            Position = 0,
                        },
                        new GradientStop()
                        {
                            Color = Color.Red,
                            Position = 1,
                        }
                }));
        }
Esempio n. 52
0
        internal static Brush ToSharpDXBrush(RenderTarget rt, System.Drawing.Brush brush)
        {
            if (brush is System.Drawing.SolidBrush)
            {
                var res = new SolidColorBrush(rt,
                    ToSharpDXColor(((System.Drawing.SolidBrush) brush).Color));
                //res.Opacity = ToPortion(((SolidBrush) brush).Color.A);
                return res;
            }

            if (brush is System.Drawing.TextureBrush)
            {
                var tb = (TextureBrush) brush;
                var sharpDXBitmap = Converter.ToSharpDXBitmap(rt, tb.Image as System.Drawing.Bitmap, 1f);
                return new SharpDX.Direct2D1.BitmapBrush(rt, sharpDXBitmap);
            }
            throw new NotSupportedException();
        }
Esempio n. 53
0
 /// <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);
 }
Esempio n. 54
0
 public void DrawGeometry(Geometry geometry, SolidColorBrush brush, int width)
 {
     d2dContext.DrawGeometry(geometry, brush, width);
 }
Esempio n. 55
0
 private void InitFont()
 {
     var directWriteFactory = new SharpDX.DirectWrite.Factory();
     _directWriteTextFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, _fontName, _fontSize) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Near };
     _directWriteFontColor = new SharpDX.Direct2D1.SolidColorBrush(_direct2DRenderTarget, _fontColor);
     directWriteFactory.Dispose();
 }
Esempio n. 56
0
        private void CreateBitmap(int width, int height)
        {


            if (_bitmap == null || (_bitmap.Size.Width < width || _bitmap.Size.Height < height))
            {

                //RenderTargetProperties rtp = new RenderTargetProperties(RenderTargetType.Default,
                //    new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied),
                //    Factory2D.DesktopDpi.Width,
                //    Factory2D.DesktopDpi.Height,
                //    RenderTargetUsage.None,
                //    FeatureLevel.Level_DEFAULT);

                try
                {
                    var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
                    _bitmap = new SharpDX.WIC.Bitmap(FactoryImaging, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                    _renderTarget = new WicRenderTarget(Factory2D, _bitmap, new RenderTargetProperties());
                    //_renderTarget = new WicRenderTarget(Factory2D, _bitmap, rtpGDI);

                    if (_brush == null)
                    {
                        _brush = new SolidColorBrush(_renderTarget, new Color4(new Color3(1, 1, 1), 1.0f));
                    }

                }
                catch (Exception exc)
                {
                    var ss = exc.Message;
                }

            }
 

        }
Esempio n. 57
0
        private void ResetBurshes(RenderContainer renderContainer)
        {
            _selectedColorBrush?.Dispose();
            _spacingColorBrush?.Dispose();
            _notMappedColorBrush?.Dispose();
            _gridColorBrush?.Dispose();

            RenderTarget target2D = renderContainer.BackBuffer.Target2D;
            _selectedColorBrush = new SolidColorBrush(target2D, SelectedColor.ToColor4(), null);
            _spacingColorBrush = new SolidColorBrush(target2D, SpacingColor.ToColor4(), null);
            _notMappedColorBrush = new SolidColorBrush(target2D, NotMappedColor.ToColor4(), null);
            _gridColorBrush = new SolidColorBrush(target2D, GridColor.ToColor4(), null);
        }
Esempio n. 58
0
 /// <summary>
 /// 使用 SharpDX 繪製線段
 /// </summary>
 /// <param name="p1x">起始點 X 座標值</param>
 /// <param name="p1y">起始點 Y 座標值</param>
 /// <param name="p2x">結束點 X 座標值</param>
 /// <param name="p2y">結束點 Y 座標值</param>
 /// <param name="brush">XMAL中用到的顏色列舉值</param>
 /// <param name="width">線條寬度</param>
 public void DrawLine(int p1x, int p1y, int p2x, int p2y, SolidColorBrush brush, int width)
 {
     d2dContext.DrawLine(new Vector2(p1x, p1y), new Vector2(p2x, p2y), brush, width);
 }
Esempio n. 59
0
 public void InitializeGlobalResources(RenderTarget target)
 {
     if (!resourcesInitialized)
     {
         SceneColorBrush = new SolidColorBrush(target, Colors.Black);
         resourcesInitialized = true;
     }
 }
        /// <summary>
        /// Inits the direct2D and direct write.
        /// </summary>
        private void InitDirect2DAndDirectWrite()
        {
            Factory2D = new SharpDX.Direct2D1.Factory();
            FactoryDWrite = new SharpDX.DirectWrite.Factory();

            var properties = new HwndRenderTargetProperties();
            properties.Hwnd = renderControl.Handle;
            properties.PixelSize = renderControl.ClientSize;
            properties.PresentOptions = PresentOptions.None;

            RenderTarget2D = new WindowRenderTarget(Factory2D, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)), properties);
            RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            SceneColorBrush = new SolidColorBrush(RenderTarget2D, new Color4(1, 0, 0, 0));
        }