コード例 #1
0
        /// <summary>
        /// Disposes of object resources.
        /// </summary>
        /// <param name="disposeManagedResources">If true, managed resources should be
        /// disposed of in addition to unmanaged resources.</param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            if (disposeManagedResources)
            {
                _d3d11Device.Dispose();
                _dxgiDevice.Dispose();
                _backBuffer.Dispose();
                _targetBitmap.Dispose();
                _backBuffer2.Dispose();
                _targetBitmap2.Dispose();
                _d2dDevice.Dispose();
                swapChain.Dispose();
                swapChain2.Dispose();
                d2dContext.Dispose();
                d2dContext2.Dispose();
                dw_Factory.Dispose();
            }

            _d3d11Device   = null;
            _dxgiDevice    = null;
            _backBuffer    = null;
            _targetBitmap  = null;
            _backBuffer2   = null;
            _targetBitmap2 = null;
            _d2dDevice     = null;
            swapChain      = null;
            swapChain2     = null;
            d2dContext     = null;
            d2dContext2    = null;
            dw_Factory     = null;
        }
コード例 #2
0
ファイル: MainWindow.cs プロジェクト: Rafka86/HeatSimulator
        private void ReleaseResources()
        {
            ReleaseD2DObjects();
            ReleaseRenderingObjects();

            void ReleaseD2DObjects()
            {
                renderTarget2d?.Dispose();
                surface?.Dispose();
                renderView?.Dispose();
                backBuffer?.Dispose();
                swapChain?.Dispose();
                device?.Dispose();
                factoryWrite?.Dispose();
                factory2d?.Dispose();
                factory?.Dispose();
            }

            void ReleaseRenderingObjects()
            {
                foreach (var cell in cells)
                {
                    cell.Dispose();
                }
                textFormat?.Dispose();
                sColorBrush?.Dispose();
            }
        }
コード例 #3
0
        public void Dispose()
        {
            foreach (var grad in verticalGradientCache.Values)
            {
                grad.Dispose();
            }
            verticalGradientCache.Clear();

            if (renderTarget != null)
            {
                renderTarget.Dispose();
                renderTarget = null;
            }

            if (directWriteFactory != null)
            {
                directWriteFactory.Dispose();
                directWriteFactory = null;
            }

            if (factory != null)
            {
                factory.Dispose();
                factory = null;
            }
        }
コード例 #4
0
 public override void Dispose()
 {
     if (Disposed)
     {
         return;
     }
     Program.MainLog.AddLong(0, MessageType.MSG, "Disposing D2D Renderer",
                             "Render Target: " + mainRenderTarget.NativePointer
                             + "\nFactory: " + factory.NativePointer);
     refTrack.Remove(this);
     Disposed = true;
     mainRenderTarget.Dispose();
     factoryAccesCount--;
     if (factoryAccesCount <= 0)
     {
         Program.MainLog.Add(MessageType.MSG, "Diposing Direct Write Factory {0}", writeFactory.NativePointer);
         writeFactory.Dispose();
         Program.MainLog.Add(MessageType.MSG, "Disposing D2D Factory");
         factory.Dispose();
     }
     foreach (var b in brushes)
     {
         b.Value.Dispose();
     }
     if (refTrack.Count == 0)
     {
         DisposeStatic();
     }
 }
コード例 #5
0
 static void Dispose()
 {
     target.Dispose();
     d2dFactory.Dispose();
     writeFactory.Dispose();
     foreach (var pair in brushes)
     {
         pair.Value.Dispose();
     }
 }
コード例 #6
0
        /// <summary>
        ///     Do not call if you use OverlayWindow class
        /// </summary>
        public void Dispose()
        {
            DeleteLayoutContainer();

            _layoutContainer = null;

            _fontFactory.Dispose();
            _factory.Dispose();
            _device.Dispose();
        }
コード例 #7
0
        /// <inheritdoc/>
        public void Import(SpriteFontAsset options, List <char> characters)
        {
            fontSource = options.FontSource.GetFontPath();
            if (string.IsNullOrEmpty(fontSource))
            {
                return;
            }

            // Get the msdfgen.exe location
            var msdfgen = ToolLocator.LocateTool("msdfgen.exe") ?? throw new AssetException("Failed to compile a font asset, msdfgen was not found.");

            msdfgenExe = msdfgen.FullPath;
            tempDir    = $"{Environment.GetEnvironmentVariable("TEMP")}\\";

            var factory = new Factory();

            FontFace fontFace = options.FontSource.GetFontFace();

            var fontMetrics = fontFace.Metrics;

            // Create a bunch of GDI+ objects.
            var fontSize = options.FontType.Size;

            var glyphList = new List <Glyph>();

            // Remap the LineMap coming from the font with a user defined remapping
            // Note:
            // We are remapping the lineMap to allow to shrink the LineGap and to reposition it at the top and/or bottom of the
            // font instead of using only the top
            // According to http://stackoverflow.com/questions/13939264/how-to-determine-baseline-position-using-directwrite#comment27947684_14061348
            // (The response is from a MSFT employee), the BaseLine should be = LineGap + Ascent but this is not what
            // we are experiencing when comparing with MSWord (LineGap + Ascent seems to offset too much.)
            //
            // So we are first applying a factor to the line gap:
            //     NewLineGap = LineGap * LineGapFactor
            var lineGap = fontMetrics.LineGap * options.LineGapFactor;

            // Store the font height.
            LineSpacing = (float)(lineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // And then the baseline is also changed in order to allow the linegap to be distributed between the top and the
            // bottom of the font:
            //     BaseLine = NewLineGap * LineGapBaseLineFactor
            BaseLine = (float)(lineGap * options.LineGapBaseLineFactor + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // Generate SDF bitmaps for each character in turn.
            foreach (var character in characters)
            {
                glyphList.Add(ImportGlyph(fontFace, character, fontMetrics, fontSize));
            }

            Glyphs = glyphList;

            factory.Dispose();
        }
コード例 #8
0
        public InfoText(SharpDX.Direct3D11.Device device)
        {
            _immediateContext = device.ImmediateContext;
            rect.Size         = new Size2F(Width, Height);

            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);

            factoryWic.Dispose();

            var factory2D = new SharpDX.Direct2D1.Factory();

            _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties);
            _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default;
            factory2D.Dispose();

            var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared);

            _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20);
            factoryDWrite.Dispose();

            _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
                }
            });
        }
コード例 #9
0
ファイル: Canvas.DxOverlay.cs プロジェクト: morelli690/Shark2
 /// <summary>
 /// Dispose anything to do with the overlay form
 /// </summary>
 private static void DisposeOverlayComponents()
 {
     _renderTarget.Dispose();
     _renderForm.Dispose();
     _newDevice.ImmediateContext.ClearState();
     _newDevice.ImmediateContext.Flush();
     _newDevice.Dispose();
     _newSwapChain.Dispose();
     _fontFactory.Dispose();
     _font.Dispose();
 }
コード例 #10
0
ファイル: Sharp2D.cs プロジェクト: ttvAmavisca/rc_car
        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();
        }
 public void Dispose()
 {
     DisposeDictionaryElements(_bitmaps);
     DisposeDictionaryElements(_ninePartsBitmaps);
     DisposeDictionaryElements(_decodedBitmaps);
     DisposeDictionaryElements(_decodedNinePartsBitmaps);
     DisposeDictionaryElements(_solidColorBrushes);
     DisposeDictionaryElements(_textFormats);
     _writeFactory.Dispose();
     _imagingFactory.Dispose();
 }
コード例 #12
0
 private void DisposeDirectXResources()
 {
     _textFormat.Dispose();
     _dwFactory.Dispose();
     _renderTarget.Dispose();
     _renderTargetView.Dispose();
     _d2DFactory.Dispose();
     _swapChain.Dispose();
     _d3DDeviceContext.Dispose();
     _d3DDevice.Dispose();
 }
コード例 #13
0
        private void StartRendering()
        {
            this.renderTask = Task.Run(() => {
                var colorBackground = new SharpDX.Mathematics.Interop.RawColor4(0, 0, 0, 1);
                var colorText       = new SharpDX.Mathematics.Interop.RawColor4(255, 255, 255, 1);

                SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory();

                var textFormat = new TextFormat(factory, "Arial", 100);

                while (!this.stopRendering)
                {
                    if (this.CanvasSize != this.ClientRectangle.Size)
                    {
                        this.ResizeSwapChain(this.Width, this.Height);
                    }

                    SolidColorBrush brush = new SolidColorBrush(painter, colorText);

                    device.ImmediateContext.ClearRenderTargetView(this.targetView, colorBackground);

                    var g  = System.Drawing.Graphics.FromHwnd(this.TargetHandle);
                    var dc = this.surface.GetDC(new SharpDX.Mathematics.Interop.RawBool(true));

                    var size = g.VisibleClipBounds.Size.ToSize();

                    BitBlt(dc, 0, 0, size.Width, size.Height, g.GetHdc(), 0, 0, TernaryRasterOperations.SRCCOPY);

                    g.ReleaseHdc();
                    g.Dispose();

                    this.surface.ReleaseDC();

                    this.painter.BeginDraw();

                    this.painter.DrawText(this.fpsCounter.GetFps().ToString(),
                                          textFormat, new SharpDX.Mathematics.Interop.RawRectangleF(0, 0, 500, 500),
                                          brush);

                    this.painter.EndDraw();

                    brush.Dispose();

                    this.fpsCounter.Update();

                    this.swapChain.Present(0, PresentFlags.None);
                }

                textFormat.Dispose();
                factory.Dispose();
            });
        }
コード例 #14
0
 private void DestroyInstance()
 {
     try
     {
         _sharedBrush.Dispose();
         _fontFactory.Dispose();
         _factory.Dispose();
         _device.Dispose();
     }
     catch
     {
     }
 }
コード例 #15
0
        public override void DestroyDevice()
        {
            foreach (string key in fonts.Keys)
            {
                GetFont(key).Dispose();
            }
            fonts.Clear();

            factory.Dispose();
            fontFactory.Dispose();
            device.Dispose();
            this.device = null;
        }
コード例 #16
0
        public override void Dispose()
        {
            foreach (var textLayout in TextFormats.Values)
            {
                textLayout.Dispose();
            }

            FontCollection.Dispose();
            FontLoader.Dispose();
            SolidColorBrush.Dispose();

            DirectWriteFactory.Dispose();
        }
コード例 #17
0
ファイル: XResource.cs プロジェクト: mxq00812314/FlysEngine
        public virtual void Dispose()
        {
            ReleaseDeviceResources();

            TransitionLibrary.Dispose();
            AnimationManager.Dispose();

            TextLayouts.Dispose();
            TextFormats.Dispose();
            Direct2DFactory.Dispose();
            DWriteFactory.Dispose();
            WICFactory.Dispose();
        }
コード例 #18
0
ファイル: InfoText.cs プロジェクト: jdoyle1983/BulletSharp
        public InfoText(SharpDX.Direct3D11.Device device)
        {
            _immediateContext = device.ImmediateContext;
            rect.Size = new Size2F(Width, Height);

            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);
            factoryWic.Dispose();

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

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

            _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
                }
            });
        }
コード例 #19
0
        /// <summary>
        /// Do not call if you use OverlayWindow class
        /// </summary>
        public void Dispose()
        {
            this.DeleteBrushContainer();
            this.DeleteFontContainer();
            this.DeleteLayoutContainer();

            this.BrushContainer  = null;
            this.FontContainer   = null;
            this.LayoutContainer = null;

            fontFactory.Dispose();
            factory.Dispose();
            device.Dispose();
        }
コード例 #20
0
        /// <summary>
        ///     Do not call if you use OverlayWindow class
        /// </summary>
        public void Dispose()
        {
            DeleteBrushContainer();
            DeleteFontContainer();
            DeleteLayoutContainer();

            _brushContainer  = null;
            _fontContainer   = null;
            _layoutContainer = null;

            CurrentBitmap.Dispose();
            _fontFactory.Dispose();
            _factory.Dispose();
            _device.Dispose();
        }
コード例 #21
0
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (var kvp in _textFormats)
                {
                    kvp.Value.Dispose();
                }
                _fontFactory.Dispose();

                foreach (var kvp in _brushes)
                {
                    kvp.Value.Dispose();
                }
            }
        }
コード例 #22
0
ファイル: Direct2DRenderer1.cs プロジェクト: troniac/OldNewGG
        private void setupInstance(bool deleteOld = false)
        {
            if (deleteOld)
            {
                try
                {
                    _brush.Dispose();
                    _font.Dispose();

                    _fontFactory.Dispose();
                    _factory.Dispose();
                    _device.Dispose();
                }
                catch
                {
                }
            }

            _factory     = new Factory(SharpDX.Direct2D1.FactoryType.MultiThreaded, DebugLevel.None);
            _fontFactory = new FontFactory();

            RECT bounds = default(RECT);

            User32.GetWindowRect(TargetHandle, out bounds);

            _targetProperties = new HwndRenderTargetProperties()
            {
                Hwnd           = TargetHandle,
                PixelSize      = new Size2(Math.Abs(bounds.Right - bounds.Left), Math.Abs(bounds.Bottom - bounds.Top)),
                PresentOptions = VSync ? PresentOptions.None : PresentOptions.Immediately
            };

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

            _device = new WindowRenderTarget(_factory, renderTargetProperties, _targetProperties);

            _device.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Aliased;
            _device.AntialiasMode     = AntialiasMode.Aliased;

            _brush = new SolidColorBrush(_device, new RawColor4(0, 0, 0, 0));
        }
コード例 #23
0
ファイル: SharpRender.cs プロジェクト: Garados007/Graphix
        public void Dispose()
        {
            brush.Dispose();

            wrFactory.Dispose();
            target.Dispose();
            bb.Dispose();
            fac.Dispose();
            d2dDevice.Dispose();
            dxgiFactory2.Dispose();
            dxgiAdapter.Dispose();
            dxgiDevice2.Dispose();
            defDevice.Dispose();
            d3device.Dispose();
            swapChain.Dispose();
            d2dContext.Dispose();
        }
コード例 #24
0
ファイル: TrueTypeImporter.cs プロジェクト: Hengle/xenko
        public void Import(SpriteFontAsset options, List <char> characters)
        {
            var factory = new Factory();

            // try to get the font face from the source file if not null
            FontFace fontFace = !string.IsNullOrEmpty(options.Source) ? GetFontFaceFromSource(factory, options) : GetFontFaceFromSystemFonts(factory, options);

            var fontMetrics = fontFace.Metrics;

            // Create a bunch of GDI+ objects.
            var fontSize = FontHelper.PointsToPixels(options.Size);

            var glyphList = new List <Glyph>();

            // Remap the LineMap coming from the font with a user defined remapping
            // Note:
            // We are remapping the lineMap to allow to shrink the LineGap and to reposition it at the top and/or bottom of the
            // font instead of using only the top
            // According to http://stackoverflow.com/questions/13939264/how-to-determine-baseline-position-using-directwrite#comment27947684_14061348
            // (The response is from a MSFT employee), the BaseLine should be = LineGap + Ascent but this is not what
            // we are experiencing when comparing with MSWord (LineGap + Ascent seems to offset too much.)
            //
            // So we are first applying a factor to the line gap:
            //     NewLineGap = LineGap * LineGapFactor
            var lineGap = fontMetrics.LineGap * options.LineGapFactor;

            // Store the font height.
            LineSpacing = (float)(lineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // And then the baseline is also changed in order to allow the linegap to be distributed between the top and the
            // bottom of the font:
            //     BaseLine = NewLineGap * LineGapBaseLineFactor
            BaseLine = (float)(lineGap * options.LineGapBaseLineFactor + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // Rasterize each character in turn.
            foreach (var character in characters)
            {
                glyphList.Add(ImportGlyph(factory, fontFace, character, fontMetrics, fontSize, options.AntiAlias));
            }

            Glyphs = glyphList;

            factory.Dispose();
        }
コード例 #25
0
ファイル: EmojiTest.cs プロジェクト: thenfour/PetsciiMapgen
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             d2dContext.Dispose();
             dwFactory.Dispose();
             imagingFactory.Dispose();
             d2dDevice.Dispose();
             dxgiDevice.Dispose();
             d3dDevice.Dispose();
             defaultDevice.Dispose();
             textBrush.Dispose();
             textFormat.Dispose();
         }
         disposedValue = true;
     }
 }
コード例 #26
0
ファイル: FontData.cs プロジェクト: MelloRin/D3DwithinCS
        private void InitFont()
        {
            Factory directWriteFactory = new Factory();

            /*FontLoader fontDataLoader = new FontLoader(directWriteFactory);
             * FontCollection fontCollection = new FontCollection(directWriteFactory, fontDataLoader, fontDataLoader.getDataStream());*/

            //CurrentTextFormat = new TextFormat(FactoryDWrite, FontFamilyName, CurrentFontCollection, FontWeight.Normal, FontStyle.Normal, FontStretch.Normal, 64)
            //{ TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center };

            _directWriteTextFormat = new TextFormat(directWriteFactory, fontName, fontSize)
            {
                TextAlignment = TextAlignment.Leading, ParagraphAlignment = ParagraphAlignment.Near
            };

            Console.WriteLine("현재 폰트명 : {0}", _directWriteTextFormat.FontFamilyName);

            _directWriteFontColor = new SolidColorBrush(renderTarget, fontColor);
            directWriteFactory.Dispose();
        }
コード例 #27
0
        protected void DisposeDirectXResources()
        {
            PreDestroyDirectXResources();
            SharedBrush.Dispose();
            BackgroundBrush.Dispose();
            ForegroundBrush.Dispose();
            CorrectColorBrush.Dispose();
            WrongColorBrush.Dispose();

            InputTextFormat.Dispose();
            ButtonLabelTextFormat.Dispose();
            SubtitleTextFormat.Dispose();
            CueTextFormat.Dispose();

            DwFactory.Dispose();
            RenderTarget.Dispose();
            RenderTargetView.Dispose();
            D2DFactory.Dispose();
            SwapChain.Dispose();
            D3DDeviceContext.Dispose();
            D3DDevice.Dispose();
        }
コード例 #28
0
        public void Dispose()
        {
            this.faceCamera.Stop();

            // Release all resources
            drawingStateBlock.Dispose();
            renderTargetView.Dispose();
            d2dRenderTarget.Dispose();
            backBuffer.Dispose();
            device.ImmediateContext.ClearState();
            device.ImmediateContext.Flush();
            device.Dispose();
            device.Dispose();
            swapChain.Dispose();
            d2dFactory.Dispose();
            dwFactory.Dispose();
            SceneColorBrush.Dispose();
            TextFormat.Dispose();
            drawingStateBlock.Dispose();
            facePointGeometry.Dispose();
            facePointBrush.Dispose();
        }
コード例 #29
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _hudTextFormat.Dispose();
                _hudYellow.Dispose();
                _hudWhite.Dispose();

                _fontCollection.Dispose();
                _fontLoader.Dispose();
                _dwFactory.Dispose();

                _texResMan.Dispose();
                _spriteResMan.Dispose();

                _swapChain.Dispose();
                _d2dTarget.Dispose();
                _d2dFactory.Dispose();
                _d3dContext.Dispose();
                _d2dContext.Dispose();
                _device.Dispose();
            }
        }
コード例 #30
0
        /// <summary>
        /// 取得字符对应的宽度
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        private float GetCharacterWidth(Character character)
        {
            DWriteFactory dwFactory  = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            Vector2       offset     = new Vector2(0.0f, 0.0f);
            TextFormat    textFormat = new TextFormat(dwFactory,
                                                      character.font.FontFamily.Name,
                                                      character.font.Bold ? SharpDX.DirectWrite.FontWeight.Bold : SharpDX.DirectWrite.FontWeight.Regular,
                                                      character.font.Italic ? SharpDX.DirectWrite.FontStyle.Italic : SharpDX.DirectWrite.FontStyle.Normal,
                                                      character.font.Size);
            TextLayout textLayout = new TextLayout(dwFactory,
                                                   "好" + character.content,
                                                   textFormat,
                                                   this.pageWidth,
                                                   this.pageHeight);

            textLayout.SetUnderline(character.font.Underline, new TextRange(0, character.content.Length));
            textLayout.SetFontStyle(character.font.Italic ? FontStyle.Italic : FontStyle.Normal, new TextRange(0, character.content.Length));
            textLayout.SetFontWeight(character.font.Bold ? FontWeight.Bold : FontWeight.Normal, new TextRange(0, character.content.Length));
            ClusterMetrics[] clusterMetrics = textLayout.GetClusterMetrics();

            float result          = 0.0f;
            float prefixCharWidth = clusterMetrics[0].Width;

            foreach (ClusterMetrics v in clusterMetrics)
            {
                result += v.Width;
            }

            dwFactory.Dispose();
            textFormat.Dispose();
            textLayout.Dispose();
            dwFactory  = null;
            textFormat = null;
            textLayout = null;

            return(result - prefixCharWidth);
        }
コード例 #31
0
        static void over()
        {
            var inputPath  = "Input.png";
            var outputPath = "output.png";

            // 그래픽을 랜더링할 장비를 추가 - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.None);
            var d3dDevice  = defaultDevice.QueryInterface <d3d.Device1>(); //get a refer to the D3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface <dxgi.Device1>();    //get a refer to the DXGI device
            var d2dDevice  = new d2.Device(dxgiDevice);

            // DeviceContext를 초기화. D2D 렌더링 타겟이 될 것이고 모든 렌더링 작업을 허용
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);
            var dwFactory  = new dw.Factory();


            //D2D, WIC 둘 다 지원되는 픽셀 형식 지정
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            //RGBA형식 사용
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;



            //이미지 로딩
            var imagingFactory = new wic.ImagingFactory2();
            var decoder        = new wic.PngBitmapDecoder(imagingFactory);
            var inputStream    = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read);

            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);



            //다이렉트2D가 사용할수 있도록 디코딩
            var formatConverter = new wic.FormatConverter(imagingFactory);

            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);


            //기본 이미지를 D2D이미지로 로드
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            //이미지 크기 저장
            var inputImageSize = formatConverter.Size;
            var pixelWidth     = inputImageSize.Width;
            var pixelHeight    = inputImageSize.Height;


            //Effect1 : BitpmapSource - 디코딩된 이미지 데이터를 가져오고 BitmapSource 가져오기
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);

            bitmapSourceEffect.WicBitmapSource = formatConverter;



            // Effect 2 : GaussianBlur - bitmapsource에 가우시안블러 효과 적용
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);

            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;



            //overlay text setup
            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f);

            //draw a long text to show the automatic line wrapping
            var textToDraw = "sime ling text..." + "text" + "dddd";

            //create the text layout - this imroves the drawing performance for static text
            // as the glyph positions are precalculated
            //윤곽선 글꼴 데이터에서 글자 하나의 모양에 대한 기본 단위를 글리프(glyph)라고 한다
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            SharpDX.Mathematics.Interop.RawColor4 color = new SharpDX.Mathematics.Interop.RawColor4(255, 255, 255, 1);
            var textBrush = new d2.SolidColorBrush(d2dContext, color);



            //여기서부터 다시

            //render target setup

            //create the d2d bitmap description using default flags and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);

            d2dContext.Target = d2dRenderTarget; //associate bitmap with the d2d context



            //Drawing

            //slow preparations - fast drawing
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect, new SharpDX.Mathematics.Interop.RawVector2(100f, 100f));
            d2dContext.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2(50f, 50f), textLayout, textBrush);
            d2dContext.EndDraw();

            //Image save

            //delete the output file if it already exists
            if (System.IO.File.Exists(outputPath))
            {
                System.IO.File.Delete(outputPath);
            }

            //use the appropiate overload to write either to tream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            //select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);

            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            //this is the trick to write d2d1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);

            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

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

            //cleanup

            //dispose everything and free used resources
            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            //gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            //save
            System.Diagnostics.Process.Start(outputPath);
        }
コード例 #32
0
        public void Import(SpriteFontAsset options, List<char> characters)
        {
            var factory = new Factory();

            // try to get the font face from the source file if not null
            FontFace fontFace = !string.IsNullOrEmpty(options.Source) ? GetFontFaceFromSource(factory, options) : GetFontFaceFromSystemFonts(factory, options);
            
            var fontMetrics = fontFace.Metrics;

            // Create a bunch of GDI+ objects.
            var fontSize = FontHelper.PointsToPixels(options.Size);

            var glyphList = new List<Glyph>();

            // Remap the LineMap coming from the font with a user defined remapping
            // Note:
            // We are remapping the lineMap to allow to shrink the LineGap and to reposition it at the top and/or bottom of the 
            // font instead of using only the top
            // According to http://stackoverflow.com/questions/13939264/how-to-determine-baseline-position-using-directwrite#comment27947684_14061348
            // (The response is from a MSFT employee), the BaseLine should be = LineGap + Ascent but this is not what
            // we are experiencing when comparing with MSWord (LineGap + Ascent seems to offset too much.)
            //
            // So we are first applying a factor to the line gap:
            //     NewLineGap = LineGap * LineGapFactor
            var lineGap = fontMetrics.LineGap * options.LineGapFactor;

            // Store the font height.
            LineSpacing = (float)(lineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // And then the baseline is also changed in order to allow the linegap to be distributed between the top and the 
            // bottom of the font:
            //     BaseLine = NewLineGap * LineGapBaseLineFactor
            BaseLine = (float)(lineGap * options.LineGapBaseLineFactor + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // Rasterize each character in turn.
            foreach (var character in characters)
                glyphList.Add(ImportGlyph(factory, fontFace, character, fontMetrics, fontSize, options.AntiAlias));

            Glyphs = glyphList;

            factory.Dispose();
        }
コード例 #33
0
ファイル: Sharp2D.cs プロジェクト: chantsunman/SharpDX_Demo
 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();
 }
コード例 #34
0
ファイル: Direct2D.cs プロジェクト: BEEden/GdiBench
        public static MemoryStream Resize(System.IO.Stream source, int maxwidth, int maxheight, Action beforeDrawImage, Action afterDrawImage)
        {
            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Warp,
                                                              d3d.DeviceCreationFlags.BgraSupport | d3d.DeviceCreationFlags.SingleThreaded | d3d.DeviceCreationFlags.PreventThreadingOptimizations);

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            var decoder = new wic.BitmapDecoder(imagingFactory,source, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            //Calculate size
            var resultSize = MathUtil.ScaleWithin(inputImageSize.Width,inputImageSize.Height,maxwidth,maxheight);
            var newWidth = resultSize.Item1;
            var newHeight = resultSize.Item2;

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(newWidth, newHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            var bitmapSourceEffect = new d2.Effects.BitmapSourceEffect(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            beforeDrawImage();
            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.Transform = Matrix3x2.Scaling(new Vector2((float)(newWidth / (float)inputImageSize.Width), (float)(newHeight / (float)inputImageSize.Height)));
            d2dContext.DrawImage(bitmapSourceEffect, d2.InterpolationMode.HighQualityCubic);
            d2dContext.EndDraw();
            afterDrawImage();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var ms = new MemoryStream();

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory,ms);

            // select the image encoding format HERE
            var encoder = new wic.JpegBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(newWidth, newHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96,  0, 0, newWidth, newHeight));

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

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            formatConverter.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();
            return ms;
        }
コード例 #35
0
ファイル: Program.cs プロジェクト: MaybeMars/SharpDX-Samples
        static void Main()
        {
            // input and output files are supposed to be in the program folder
            var inputPath = "Input.png";
            var outputPath = "Output.png";

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // INITIALIZATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // initialize the D3D device which will allow to render to image any graphics - 3D or 2D
            var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware,
                                                              d3d.DeviceCreationFlags.VideoSupport
                                                              | d3d.DeviceCreationFlags.BgraSupport
                                                              | d3d.DeviceCreationFlags.Debug); // take out the Debug flag for better performance

            var d3dDevice = defaultDevice.QueryInterface<d3d.Device1>(); // get a reference to the Direct3D 11.1 device
            var dxgiDevice = d3dDevice.QueryInterface<dxgi.Device>(); // get a reference to DXGI device

            var d2dDevice = new d2.Device(dxgiDevice); // initialize the D2D device

            var imagingFactory = new wic.ImagingFactory2(); // initialize the WIC factory

            // initialize the DeviceContext - it will be the D2D render target and will allow all rendering operations
            var d2dContext = new d2.DeviceContext(d2dDevice, d2.DeviceContextOptions.None);

            var dwFactory = new dw.Factory();

            // specify a pixel format that is supported by both D2D and WIC
            var d2PixelFormat = new d2.PixelFormat(dxgi.Format.R8G8B8A8_UNorm, d2.AlphaMode.Premultiplied);
            // if in D2D was specified an R-G-B-A format - use the same for wic
            var wicPixelFormat = wic.PixelFormat.Format32bppPRGBA;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE LOADING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var decoder = new wic.PngBitmapDecoder(imagingFactory); // we will load a PNG image
            var inputStream = new wic.WICStream(imagingFactory, inputPath, NativeFileAccess.Read); // open the image file for reading
            decoder.Initialize(inputStream, wic.DecodeOptions.CacheOnLoad);

            // decode the loaded image to a format that can be consumed by D2D
            var formatConverter = new wic.FormatConverter(imagingFactory);
            formatConverter.Initialize(decoder.GetFrame(0), wicPixelFormat);

            // load the base image into a D2D Bitmap
            //var inputBitmap = d2.Bitmap1.FromWicBitmap(d2dContext, formatConverter, new d2.BitmapProperties1(d2PixelFormat));

            // store the image size - output will be of the same size
            var inputImageSize = formatConverter.Size;
            var pixelWidth = inputImageSize.Width;
            var pixelHeight = inputImageSize.Height;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // EFFECT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // Effect 1 : BitmapSource - take decoded image data and get a BitmapSource from it
            var bitmapSourceEffect = new d2.Effects.BitmapSource(d2dContext);
            bitmapSourceEffect.WicBitmapSource = formatConverter;

            // Effect 2 : GaussianBlur - give the bitmapsource a gaussian blurred effect
            var gaussianBlurEffect = new d2.Effects.GaussianBlur(d2dContext);
            gaussianBlurEffect.SetInput(0, bitmapSourceEffect.Output, true);
            gaussianBlurEffect.StandardDeviation = 5f;

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // OVERLAY TEXT SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var textFormat = new dw.TextFormat(dwFactory, "Arial", 15f); // create the text format of specified font configuration

            // draw a long text to show the automatic line wrapping
            var textToDraw = "Some long text to show the drawing of preformatted "
                             + "glyphs using DirectWrite on the Direct2D surface."
                             + " Notice the automatic wrapping of line if it exceeds desired width.";

            // create the text layout - this improves the drawing performance for static text
            // as the glyph positions are precalculated
            var textLayout = new dw.TextLayout(dwFactory, textToDraw, textFormat, 300f, 1000f);

            var textBrush = new d2.SolidColorBrush(d2dContext, Color.LightGreen);

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // RENDER TARGET SETUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // create the d2d bitmap description using default flags (from SharpDX samples) and 96 DPI
            var d2dBitmapProps = new d2.BitmapProperties1(d2PixelFormat, 96, 96, d2.BitmapOptions.Target | d2.BitmapOptions.CannotDraw);

            // the render target
            var d2dRenderTarget = new d2.Bitmap1(d2dContext, new Size2(pixelWidth, pixelHeight), d2dBitmapProps);
            d2dContext.Target = d2dRenderTarget; // associate bitmap with the d2d context

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // DRAWING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // slow preparations - fast drawing:
            d2dContext.BeginDraw();
            d2dContext.DrawImage(gaussianBlurEffect);
            d2dContext.DrawTextLayout(new Vector2(5f, 5f), textLayout, textBrush);
            d2dContext.EndDraw();

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // IMAGE SAVING ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // delete the output file if it already exists
            if (System.IO.File.Exists(outputPath)) System.IO.File.Delete(outputPath);

            // use the appropiate overload to write either to stream or to a file
            var stream = new wic.WICStream(imagingFactory, outputPath, NativeFileAccess.Write);

            // select the image encoding format HERE
            var encoder = new wic.PngBitmapEncoder(imagingFactory);
            encoder.Initialize(stream);

            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);
            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(pixelWidth, pixelHeight);
            bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);

            // this is the trick to write D2D1 bitmap to WIC
            var imageEncoder = new wic.ImageEncoder(imagingFactory, d2dDevice);
            imageEncoder.WriteFrame(d2dRenderTarget, bitmapFrameEncode, new wic.ImageParameters(d2PixelFormat, 96, 96, 0, 0, pixelWidth, pixelHeight));

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

            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // CLEANUP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            // dispose everything and free used resources

            bitmapFrameEncode.Dispose();
            encoder.Dispose();
            stream.Dispose();
            textBrush.Dispose();
            textLayout.Dispose();
            textFormat.Dispose();
            formatConverter.Dispose();
            gaussianBlurEffect.Dispose();
            bitmapSourceEffect.Dispose();
            d2dRenderTarget.Dispose();
            inputStream.Dispose();
            decoder.Dispose();
            d2dContext.Dispose();
            dwFactory.Dispose();
            imagingFactory.Dispose();
            d2dDevice.Dispose();
            dxgiDevice.Dispose();
            d3dDevice.Dispose();
            defaultDevice.Dispose();

            // show the result
            System.Diagnostics.Process.Start(outputPath);
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: Kammikazy/SharpDX-Samples
        static void Main(string[] args)
        {
            mainForm = new RenderForm("Advanced Text rendering demo");

            d2dFactory = new D2DFactory();
            dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            
            textRenderer = new CustomColorRenderer();

            CreateResources();

            var bgcolor = new Color4(0.1f,0.1f,0.1f,1.0f);

            //This is the offset where we start our text layout
            Vector2 offset = new Vector2(202.0f,250.0f);

            textFormat = new TextFormat(dwFactory, "Arial", FontWeight.Regular, FontStyle.Normal, 16.0f);
            textLayout = new TextLayout(dwFactory, introText, textFormat, 300.0f, 200.0f);

            //Apply various modifications to text
            textLayout.SetUnderline(true, new TextRange(0, 5));
            textLayout.SetDrawingEffect(greenBrush, new TextRange(10, 20));
            textLayout.SetFontSize(24.0f, new TextRange(6, 4));
            textLayout.SetFontFamilyName("Comic Sans MS", new TextRange(11,7));

            //Measure full layout
            var textSize = textLayout.Metrics;
            fullTextBackground = new RectangleF(textSize.Left + offset.X, textSize.Top + offset.Y, textSize.Width, textSize.Height);

            //Measure text to apply background to
            var metrics = textLayout.HitTestTextRange(53, 4, 0.0f, 0.0f)[0];
            textRegionRect = new RectangleF(metrics.Left + offset.X, metrics.Top + offset.Y, metrics.Width, metrics.Height);

            //Assign render target and brush to our custom renderer
            textRenderer.AssignResources(renderTarget, defaultBrush);

            RenderLoop.Run(mainForm, () =>
            {
                renderTarget.BeginDraw();
                renderTarget.Clear(bgcolor);

                renderTarget.FillRectangle(fullTextBackground, backgroundBrush);

                renderTarget.FillRectangle(textRegionRect, redBrush);

                textLayout.Draw(textRenderer, offset.X, offset.Y);

                try
                {
                    renderTarget.EndDraw();
                }
                catch
                {
                    CreateResources();
                }
            });

            d2dFactory.Dispose();
            dwFactory.Dispose();
            renderTarget.Dispose();
        }