예제 #1
0
 public override void Dispose()
 {
     View.Dispose();
     buffer.Dispose();
     DxFac.Dispose();
     base.Dispose();
 }
예제 #2
0
        protected void ReleaseResources()
        {
            _bitmap.Dispose();
            _bitmap = null;

            _renderTarget.Dispose();
            _renderTarget = null;
        }
예제 #3
0
 public override void Dispose()
 {
     Stream?.Dispose();
     base.Dispose();
     if (PrePairedFrame?.IsDisposed == false)
     {
         PrePairedFrame.Dispose();
     }
 }
예제 #4
0
 public override void Render()
 {
     if (Source.Updated)
     {
         _Pelete?.Dispose();
         _Pelete = Source.Output;
     }
     using (Image PrepairedImage = Output(HostDC))
         HostDC.DrawImage(PrepairedImage, new RawVector2(_Position.X, _Position.Y), null, SharpDX.Direct2D1.InterpolationMode.Linear, CompositeMode.SourceOver);
 }
        public static void EncodeImage(this d2.Bitmap target, ImageFormat imageFormat, Stream outputStream)
        {
            var width  = target.PixelSize.Width;
            var height = target.PixelSize.Height;

            var wicBitmap = new wic.Bitmap(DXGraphicsService.FactoryImaging, width, height,
                                           wic.PixelFormat.Format32bppBGR, wic.BitmapCreateCacheOption.CacheOnLoad);
            var renderTargetProperties = new d2.RenderTargetProperties(d2.RenderTargetType.Default,
                                                                       new d2.PixelFormat(Format.Unknown,
                                                                                          d2.AlphaMode.Unknown), 0, 0,
                                                                       d2.RenderTargetUsage.None,
                                                                       d2.FeatureLevel.Level_DEFAULT);
            var d2DRenderTarget = new d2.WicRenderTarget(target.Factory, wicBitmap, renderTargetProperties);

            d2DRenderTarget.BeginDraw();
            d2DRenderTarget.Clear(global::SharpDX.Color.Transparent);
            d2DRenderTarget.DrawBitmap(target, 1, d2.BitmapInterpolationMode.Linear);
            d2DRenderTarget.EndDraw();

            var stream = new wic.WICStream(DXGraphicsService.FactoryImaging, outputStream);

            // Initialize a Jpeg encoder with this stream
            var encoder = new wic.BitmapEncoder(DXGraphicsService.FactoryImaging, GetImageFormat(imageFormat));

            encoder.Initialize(stream);

            // Create a Frame encoder
            var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder);

            bitmapFrameEncode.Initialize();
            bitmapFrameEncode.SetSize(width, height);
            Guid pixelFormatGuid = wic.PixelFormat.FormatDontCare;

            bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
            bitmapFrameEncode.WriteSource(wicBitmap);

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

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

            d2DRenderTarget.Dispose();
            wicBitmap.Dispose();
        }
예제 #6
0
        public void Dispose()
        {
            if (_canvas != null)
            {
                _canvas.Dispose();
                _canvas = null;
            }

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

            if (_renderTarget != null)
            {
                _renderTarget.Dispose();
                _renderTarget = null;
            }
        }
예제 #7
0
        public void Dispose()
        {
            if (graphics != null)
            {
                graphics.Dispose();
            }

            if (dot9BitmaShadowDict != null)
            {
                foreach (var item in dot9BitmaShadowDict)
                {
                    item.Value.Dispose();
                }
                dot9BitmaShadowDict.Clear();
            }

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

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

            if (rebulidLayerList != null)
            {
                rebulidLayerList.Clear();
            }

            if (rootParent != null)
            {
                rootParent.Dispose();
            }
        }
예제 #8
0
        private void SaveToFile(D3DX direct3D, Texture2D texture, Guid format)
        {
            var stream        = new System.IO.FileStream("Output.png", System.IO.FileMode.Create);
            var textureTarget = texture;
            var textureCopy   = new Texture2D(direct3D.Device, new Texture2DDescription
            {
                Width             = (int)textureTarget.Description.Width,
                Height            = (int)textureTarget.Description.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = textureTarget.Description.Format,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });

            direct3D.DeviceContext.CopyResource(textureTarget, textureCopy);

            var dataBox = direct3D.DeviceContext.MapSubresource(
                textureCopy,
                0,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out DataStream dataStream);

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };

            var imagingFactory = new ImagingFactory2();
            var bitmap         = new SharpDX.WIC.Bitmap(
                imagingFactory,
                textureCopy.Description.Width,
                textureCopy.Description.Height,
                format,
                dataRectangle);

            using (var s = stream)
            {
                s.Position = 0;
                using (var bitmapEncoder = new PngBitmapEncoder(imagingFactory, s))
                {
                    using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                    {
                        bitmapFrameEncode.Initialize();
                        bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height);
                        var pixelFormat = SharpDX.WIC.PixelFormat.FormatDontCare;
                        bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                        bitmapFrameEncode.WriteSource(bitmap);
                        bitmapFrameEncode.Commit();
                        bitmapEncoder.Commit();
                        bitmapFrameEncode.Dispose();
                        bitmapEncoder.Dispose();
                    }
                }
            }

            direct3D.DeviceContext.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            bitmap.Dispose();
            imagingFactory.Dispose();
            dataStream.Dispose();
            stream.Dispose();
        }
예제 #9
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= (int)contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            var font = CreateFont(textDef.FontName, textDef.FontSize);

            var _currentFontSizeEm = textDef.FontSize;
            var _currentDIP        = ConvertPointSizeToDIP(_currentFontSizeEm);

            var fontColor       = textDef.FontFillColor;
            var fontAlpha       = textDef.FontAlpha;
            var foregroundColor = new Color4(fontColor.R / 255.0f,
                                             fontColor.G / 255.0f,
                                             fontColor.B / 255.0f,
                                             fontAlpha / 255.0f);

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing
                : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center
                : TextAlignment.Leading;

            var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far
                : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center
                : ParagraphAlignment.Near;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap
                : WordWrapping.NoWrap;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }

            var fontName   = font.FontFamily.FamilyNames.GetString(0);
            var textFormat = new TextFormat(FactoryDWrite, fontName,
                                            _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP);

            textFormat.TextAlignment      = textAlign;
            textFormat.ParagraphAlignment = paragraphAlign;

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height);

            var boundingRect = new RectangleF();

            // Loop through all the lines so we can find our drawing offsets
            var textMetrics = textLayout.Metrics;
            var lineCount   = textMetrics.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
            {
                return(new CCTexture2D());
            }

            // Fill out the bounding rect width and height so we can calculate the yOffset later if needed
            boundingRect.X      = 0;
            boundingRect.Y      = 0;
            boundingRect.Width  = textMetrics.Width;
            boundingRect.Height = textMetrics.Height;

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != TextAlignment.Leading)
            {
                textLayout.MaxWidth  = dimensions.Width;
                textLayout.MaxHeight = dimensions.Height;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                      // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                                  // align to center


            SharpDX.WIC.Bitmap sharpBitmap       = null;
            WicRenderTarget    sharpRenderTarget = null;
            SolidColorBrush    solidBrush        = null;

            try
            {
                // Select our pixel format
                var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;

                // create our backing bitmap
                sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                // Create the render target that we will draw to
                sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties());
                // Create our brush to actually draw with
                solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor);

                // Begin the drawing
                sharpRenderTarget.BeginDraw();

                if (textDefinition.isShouldAntialias)
                {
                    sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased;
                }

                // Clear it
                sharpRenderTarget.Clear(TransparentColor);

                // Draw the text to the bitmap
                sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush);

                // End our drawing which will commit the rendertarget to the bitmap
                sharpRenderTarget.EndDraw();

                // Debugging purposes
                //var s = "Label4";
                //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget);

                // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D
                Texture2D tex = null;

                using (var memStream = new MemoryStream())
                {
                    using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream))
                        using (var frameEncoder = new BitmapFrameEncode(encoder))
                        {
                            frameEncoder.Initialize();
                            frameEncoder.WriteSource(sharpBitmap);
                            frameEncoder.Commit();
                            encoder.Commit();
                        }
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream);
                }

                // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it.
                return(new CCTexture2D(tex));
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text.  Message: {0}", exc.StackTrace);
            }
            finally
            {
                if (sharpBitmap != null)
                {
                    sharpBitmap.Dispose();
                    sharpBitmap = null;
                }

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

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

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

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

            // If we have reached here then something has gone wrong.
            return(new CCTexture2D());
        }
예제 #10
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
                return new CCTexture2D();

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;
            textDef.FontSize *= contentScaleFactorWidth;
            textDef.Dimensions.Width *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            var font = CreateFont(textDef.FontName, textDef.FontSize);
            if (font == null)
            {
                CCLog.Log("Can not create font {0} with size {1}.", textDef.FontName, textDef.FontSize);
                return new CCTexture2D();
            }


            var _currentFontSizeEm = textDef.FontSize;
            var _currentDIP = ConvertPointSizeToDIP(_currentFontSizeEm);

            // color
            var foregroundColor = Color4.White;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? TextAlignment.Trailing
                : (CCTextAlignment.Center == horizontalAlignment) ? TextAlignment.Center
                : TextAlignment.Leading;

            var paragraphAlign = (CCVerticalTextAlignment.Bottom == vertAlignment) ? ParagraphAlignment.Far
                : (CCVerticalTextAlignment.Center == vertAlignment) ? ParagraphAlignment.Center
                : ParagraphAlignment.Near;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? WordWrapping.Wrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? WordWrapping.Wrap
                : WordWrapping.NoWrap;

            // LineBreak
            // TODO: Find a way to specify the type of line breaking if possible.

            var dimensions = new CCSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;
            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable = false;
            }

            var fontName = font.FontFamily.FamilyNames.GetString(0);
            var textFormat = new TextFormat(FactoryDWrite, fontName,
                _currentFontCollection, FontWeight.Regular, FontStyle.Normal, FontStretch.Normal, _currentDIP);

            textFormat.TextAlignment = textAlign;
            textFormat.ParagraphAlignment = paragraphAlign;

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, dimensions.Width, dimensions.Height);

            var boundingRect = new RectangleF();

            // Loop through all the lines so we can find our drawing offsets
            var textMetrics = textLayout.Metrics;
            var lineCount = textMetrics.LineCount;

            // early out if something went wrong somewhere and nothing is to be drawn
            if (lineCount == 0)
                return new CCTexture2D();

            // Fill out the bounding rect width and height so we can calculate the yOffset later if needed
            boundingRect.X = 0; 
            boundingRect.Y = 0; 
            boundingRect.Width = textMetrics.Width;
            boundingRect.Height = textMetrics.Height;

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Recreate our layout based on calculated dimensions so that we can draw the text correctly
            // in our image when Alignment is not Left.
            if (textAlign != TextAlignment.Leading)
            {
                textLayout.MaxWidth = dimensions.Width;
                textLayout.MaxHeight = dimensions.Height;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement
                || boundingRect.Bottom >= dimensions.Height) ? dimensions.Height - boundingRect.Bottom  // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                    // align to top
                : (imageHeight - boundingRect.Bottom) * 0.5f;                                   // align to center


            SharpDX.WIC.Bitmap sharpBitmap = null;
            WicRenderTarget sharpRenderTarget = null;
            SolidColorBrush solidBrush = null;

            try
            {
                // Select our pixel format
                var pixelFormat = SharpDX.WIC.PixelFormat.Format32bppPRGBA;

                // create our backing bitmap
                sharpBitmap = new SharpDX.WIC.Bitmap(FactoryImaging, imageWidth, imageHeight, pixelFormat, BitmapCreateCacheOption.CacheOnLoad);

                // Create the render target that we will draw to
                sharpRenderTarget = new WicRenderTarget(Factory2D, sharpBitmap, new RenderTargetProperties());
                // Create our brush to actually draw with
                solidBrush = new SolidColorBrush(sharpRenderTarget, foregroundColor);

                // Begin the drawing
                sharpRenderTarget.BeginDraw();

                if (textDefinition.isShouldAntialias)
                    sharpRenderTarget.AntialiasMode = AntialiasMode.Aliased;

                // Clear it
                sharpRenderTarget.Clear(TransparentColor);

                // Draw the text to the bitmap
                sharpRenderTarget.DrawTextLayout(new Vector2(boundingRect.X, yOffset), textLayout, solidBrush);

                // End our drawing which will commit the rendertarget to the bitmap
                sharpRenderTarget.EndDraw();

                // Debugging purposes
                //var s = "Label4";
                //SaveToFile(@"C:\Xamarin\" + s + ".png", _bitmap, _renderTarget);

                // The following code creates a .png stream in memory of our Bitmap and uses it to create our Textue2D
                Texture2D tex = null;

                using (var memStream = new MemoryStream())
                {
                    using (var encoder = new PngBitmapEncoder(FactoryImaging, memStream))
                    using (var frameEncoder = new BitmapFrameEncode(encoder))
                    {
                        frameEncoder.Initialize();
                        frameEncoder.WriteSource(sharpBitmap);
                        frameEncoder.Commit();
                        encoder.Commit();
                    }
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, memStream);
                }

                // Return our new CCTexture2D created from the Texture2D which will have our text drawn on it.
                return new CCTexture2D(tex);
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel-Windows: Unable to create the backing image of our text.  Message: {0}", exc.StackTrace);
            }
            finally
            {
                if (sharpBitmap != null)
                {
                    sharpBitmap.Dispose();
                    sharpBitmap = null;
                }

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

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

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

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

            // If we have reached here then something has gone wrong.
            return new CCTexture2D();
        }
예제 #11
0
        //create a bitmap from a texture2D. DOES NOT WORK
        public static System.Drawing.Bitmap GetTextureBitmap(Device device, Texture2D tex, int mipSlice)
        {
            int w = tex.Description.Width;
            int h = tex.Description.Height;

            var textureCopy = new Texture2D(device, new Texture2DDescription
            {
                Width             = w,
                Height            = h,
                MipLevels         = tex.Description.MipLevels,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Staging,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags         = BindFlags.None,
                CpuAccessFlags    = CpuAccessFlags.Read,
                OptionFlags       = ResourceOptionFlags.None
            });
            DataStream dataStream;// = new DataStream(8 * tex.Description.Width * tex.Description.Height, true, true);

            DeviceContext context = device.ImmediateContext;

            //context.CopyResource(tex, textureCopy);
            context.CopySubresourceRegion(tex, mipSlice, null, textureCopy, 0);


            var dataBox = context.MapSubresource(
                textureCopy,
                mipSlice,
                0,
                MapMode.Read,
                SharpDX.Direct3D11.MapFlags.None,
                out dataStream);

            //int bytesize = w * h * 4;
            //byte[] pixels = new byte[bytesize];
            //dataStream.Read(pixels, 0, bytesize);
            //dataStream.Position = 0;

            var dataRectangle = new DataRectangle
            {
                DataPointer = dataStream.DataPointer,
                Pitch       = dataBox.RowPitch
            };


            ImagingFactory wicf = new ImagingFactory();

            var b = new SharpDX.WIC.Bitmap(wicf, w, h, SharpDX.WIC.PixelFormat.Format32bppBGRA, dataRectangle);


            var s = new MemoryStream();

            using (var bitmapEncoder = new PngBitmapEncoder(wicf, s))
            {
                using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder))
                {
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(b.Size.Width, b.Size.Height);
                    var pixelFormat = PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormat);
                    bitmapFrameEncode.WriteSource(b);
                    bitmapFrameEncode.Commit();
                    bitmapEncoder.Commit();
                }
            }

            context.UnmapSubresource(textureCopy, 0);
            textureCopy.Dispose();
            b.Dispose();



            s.Position = 0;
            var bmp = new System.Drawing.Bitmap(s);



            //Palette pal = new Palette(wf);
            //b.CopyPalette(pal);

            //byte[] pixels = new byte[w * h * 4];
            //b.CopyPixels(pixels, w * 4);
            //GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            //var hptr = handle.AddrOfPinnedObject();
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, w * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, hptr);
            //handle.Free();

            //System.Threading.Thread.Sleep(1000);

            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            //System.Drawing.Imaging.BitmapData data = bmp.LockBits(
            //  new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
            //  System.Drawing.Imaging.ImageLockMode.WriteOnly,
            //  System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            ////b.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            //b.CopyPixels(data.Stride, data.Scan0, data.Height * data.Stride);
            //bmp.UnlockBits(data);


            var c1 = bmp.GetPixel(10, 2);


            //dataStream.Dispose();


            return(bmp);
        }
예제 #12
0
 public override void Dispose()
 {
     buffer?.Dispose();
     base.Dispose();
 }
예제 #13
0
 public override void Dispose()
 {
     base.Dispose();
     _bitmap?.Dispose();
 }
예제 #14
0
        /// <summary>
        /// 从rss生成图像
        /// </summary>
        /// <param name="channel">从rss源获得的数据</param>
        /// <param name="path">保存图像的路径</param>
        private void GetImageFromRss(object obj)
        {
            ImageObj image    = (ImageObj)obj;
            RssInfo  rssInfo  = image.rssInfo;
            RssMedia rssMedia = image.rssMedia;
            string   fileName = "";

            if (rssInfo == null || rssMedia == null)
            {
                return;
            }

            List <Page> pages                  = GetPageListFromRss(rssInfo, rssMedia);
            var         wicFactory             = new ImagingFactory();
            var         d2dFactory             = new SharpDX.Direct2D1.Factory();
            var         dwFactory              = new SharpDX.DirectWrite.Factory();
            var         renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                            new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown),
                                                                            0,
                                                                            0,
                                                                            RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);

            var wicBitmap = new SharpDX.WIC.Bitmap(wicFactory,
                                                   pageWidth,
                                                   pageHeight,
                                                   SharpDX.WIC.PixelFormat.Format32bppBGR,
                                                   BitmapCreateCacheOption.CacheOnLoad);
            var d2dRenderTarget = new WicRenderTarget(d2dFactory,
                                                      wicBitmap,
                                                      renderTargetProperties);

            d2dRenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;
            var solidColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                      new SharpDX.Color(this.backgroundColor.R,
                                                                        this.backgroundColor.G,
                                                                        this.backgroundColor.B,
                                                                        this.backgroundColor.A));
            var textBodyBrush = new SolidColorBrush(d2dRenderTarget,
                                                    new SharpDX.Color(rssMedia.RssBodyProp.
                                                                      TextColor.R,
                                                                      rssMedia.RssBodyProp.TextColor.G,
                                                                      rssMedia.RssBodyProp.TextColor.B,
                                                                      rssMedia.RssBodyProp.TextColor.A));
            var titleColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                      new SharpDX.Color(rssMedia.RssTitleProp.TextColor.R,
                                                                        rssMedia.RssTitleProp.TextColor.G,
                                                                        rssMedia.RssTitleProp.TextColor.B,
                                                                        rssMedia.RssTitleProp.TextColor.A));
            var publishDateColorBrush = new SolidColorBrush(d2dRenderTarget,
                                                            new SharpDX.Color(rssMedia.RssPublishTimeProp.TextColor.R,
                                                                              rssMedia.RssPublishTimeProp.TextColor.G,
                                                                              rssMedia.RssPublishTimeProp.TextColor.B,
                                                                              rssMedia.RssPublishTimeProp.TextColor.A));
            TextLayout textLayout;

            try
            {
                int count = 0;

                foreach (Page page in pages)
                {
                    d2dRenderTarget.BeginDraw();
                    d2dRenderTarget.Clear(new SharpDX.Color(this.backgroundColor.R,
                                                            this.backgroundColor.G,
                                                            this.backgroundColor.B,
                                                            this.backgroundColor.A));

                    foreach (Line line in page.lines)
                    {
                        foreach (Block block in line.content)
                        {
                            TextFormat textFormat = new TextFormat(dwFactory,
                                                                   block.font.FontFamily.Name,
                                                                   block.font.Size);
                            textLayout = new TextLayout(dwFactory,
                                                        block.content,
                                                        textFormat,
                                                        block.width,
                                                        block.height);
                            switch (block.type)
                            {
                            case RssBodyType.Title:
                                textLayout.SetUnderline(rssMedia.RssTitleProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssTitleProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssTitleProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, titleColorBrush);
                                break;

                            case RssBodyType.Time:
                                textLayout.SetUnderline(rssMedia.RssPublishTimeProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssPublishTimeProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssPublishTimeProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, publishDateColorBrush);
                                break;

                            case RssBodyType.Body:
                                textLayout.SetUnderline(rssMedia.RssBodyProp.TextFont.Underline,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontStyle(rssMedia.RssBodyProp.TextFont.Italic ? FontStyle.Italic : FontStyle.Normal,
                                                        new TextRange(0, block.content.Length));
                                textLayout.SetFontWeight(rssMedia.RssBodyProp.TextFont.Bold ? FontWeight.Bold : FontWeight.Normal,
                                                         new TextRange(0, block.content.Length));
                                d2dRenderTarget.DrawTextLayout(new Vector2(block.left, block.top), textLayout, textBodyBrush);
                                break;

                            default:
                                break;
                            }
                            textFormat.Dispose();
                            textFormat = null;
                        }
                    }

                    d2dRenderTarget.EndDraw();

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fileName = string.Format("{0}{1}.jpg", path, DateTime.Now.Ticks.ToString());
                    var stream  = new WICStream(wicFactory, fileName, NativeFileAccess.Write);
                    var encoder = new PngBitmapEncoder(wicFactory);
                    encoder.Initialize(stream);
                    var bitmapFrameEncode = new BitmapFrameEncode(encoder);
                    bitmapFrameEncode.Initialize();
                    bitmapFrameEncode.SetSize(pageWidth, pageHeight);
                    var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare;
                    bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid);
                    bitmapFrameEncode.WriteSource(wicBitmap);
                    bitmapFrameEncode.Commit();
                    encoder.Commit();
                    bitmapFrameEncode.Dispose();
                    encoder.Dispose();
                    stream.Dispose();

                    Console.WriteLine("*********image count is : " + count++);
                    //发送单个图片生成事件
                    if (SingleGenerateCompleteEvent != null)
                    {
                        SingleGenerateCompleteEvent(fileName);
                    }
                }
                //发送生成完成事件
                if (GenerateCompleteEvent != null)
                {
                    GenerateCompleteEvent(path);
                    //停止线程,从字典删除
                    StopGenerate(rssMedia.CachePath);
                }
            }
            catch (ThreadAbortException aborted)
            {
                Trace.WriteLine("rss 图片生成线程终止 : " + aborted.Message);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("rss 图片生成遇到bug : " + ex.Message);
            }
            finally
            {
                wicFactory.Dispose();
                d2dFactory.Dispose();
                dwFactory.Dispose();
                wicBitmap.Dispose();
                d2dRenderTarget.Dispose();
                solidColorBrush.Dispose();
                textBodyBrush.Dispose();
                titleColorBrush.Dispose();
                publishDateColorBrush.Dispose();
                rssInfo.Dispose();
                rssMedia.Dispose();
                wicFactory            = null;
                d2dFactory            = null;
                dwFactory             = null;
                wicBitmap             = null;
                d2dRenderTarget       = null;
                solidColorBrush       = null;
                textBodyBrush         = null;
                titleColorBrush       = null;
                publishDateColorBrush = null;
                rssInfo  = null;
                rssMedia = null;
                pages.Clear();
                pages = null;
            }
        }
예제 #15
0
        public static SharpDX.Direct2D1.Bitmap RedrawRestNoteBitmapCache(RenderTarget renderTargetSource, Color color, DurationTypes durationType)
        {
            ImagingFactory factory = new ImagingFactory();

            SharpDX.Direct2D1.Factory   factory2  = new SharpDX.Direct2D1.Factory();
            SharpDX.DirectWrite.Factory factory3  = new SharpDX.DirectWrite.Factory();
            SharpDX.WIC.Bitmap          wicBitmap = new SharpDX.WIC.Bitmap(factory, 0x20, 0x30, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand);
            RenderTargetProperties      renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), 0f, 0f, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);
            WicRenderTarget             renderTarget           = new WicRenderTarget(factory2, wicBitmap, renderTargetProperties);

            try
            {
                PointF[] pathPoints;
                renderTarget.BeginDraw();
                renderTarget.Clear(new RawColor4?(Color.Transparent.ToRawColor4(1f)));
                RawVector2 pos = new RawVector2(18f, 44f);
                using (GraphicsPath path = new GraphicsPath())
                {
                    DurationTypes types = durationType;
                    if (types <= DurationTypes.Eighth)
                    {
                        switch (types)
                        {
                        case DurationTypes.The32nd:
                            pos = new RawVector2(pos.X, (pos.Y - (8f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f);
                            path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y);
                            path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 41f);
                            path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 41f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 41f));
                            path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 41f, pos.X, pos.Y);
                            DrawRestDotPart(renderTarget, pos, color);
                            DrawRestDotPart(renderTarget, new RawVector2(pos.X - 2.2f, pos.Y + 11f), color);
                            DrawRestDotPart(renderTarget, new RawVector2(pos.X - 4.4f, pos.Y + 22f), color);
                            break;

                        case DurationTypes.The16th:
                            pos = new RawVector2(pos.X, (pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f);
                            path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y);
                            path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 30f);
                            path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 30f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 30f));
                            path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 30f, pos.X, pos.Y);
                            DrawRestDotPart(renderTarget, pos, color);
                            DrawRestDotPart(renderTarget, new RawVector2(pos.X - 2.4f, pos.Y + 11f), color);
                            break;

                        case DurationTypes.Eighth:
                            goto Label_06F6;
                        }
                    }
                    else
                    {
                        switch (types)
                        {
                        case DurationTypes.Quarter:
                            pos = new RawVector2(pos.X - 11f, pos.Y - (7f * (((float)McMeasure.StaveSpacing) / 2f)));
                            path.AddLine(pos.X, pos.Y, pos.X + 7f, pos.Y + 9.5f);
                            path.AddBezier((float)(pos.X + 7f), (float)(pos.Y + 9.5f), (float)(pos.X + 3f), (float)(pos.Y + 16f), (float)(pos.X + 3f), (float)(pos.Y + 16f), (float)(pos.X + 8f), (float)(pos.Y + 24f));
                            path.AddBezier((float)(pos.X + 8f), (float)(pos.Y + 24f), (float)(pos.X - 0f), (float)(pos.Y + 21f), (float)(pos.X - 1f), (float)(pos.Y + 26f), (float)(pos.X + 4f), (float)(pos.Y + 34f));
                            path.AddBezier((float)(pos.X + 4f), (float)(pos.Y + 34f), (float)(pos.X - 8f), (float)(pos.Y + 28f), (float)(pos.X - 4f), (float)(pos.Y + 17f), (float)(pos.X + 4.5f), (float)(pos.Y + 21f));
                            path.AddLine((float)(pos.X + 4.5f), (float)(pos.Y + 21f), (float)(pos.X - 1f), (float)(pos.Y + 14f));
                            path.AddBezier((float)(pos.X - 1f), (float)(pos.Y + 14f), (float)(pos.X + 3.5f), (float)(pos.Y + 11f), (float)(pos.X + 4f), (float)(pos.Y + 7f), (float)(pos.X - 1f), (float)(pos.Y + 2f));
                            goto Label_0AD7;

                        case DurationTypes.Half:
                            pos = new RawVector2(pos.X - 8f, pos.Y - (4f * (((float)McMeasure.StaveSpacing) / 2f)));
                            path.AddLine(pos.X - 7f, pos.Y, pos.X + 7f, pos.Y);
                            path.AddLine(pos.X + 7f, pos.Y, pos.X + 7f, pos.Y - 5f);
                            path.AddLine((float)(pos.X + 7f), (float)(pos.Y - 5f), (float)(pos.X - 7f), (float)(pos.Y - 5f));
                            path.AddLine(pos.X - 7f, pos.Y - 5f, pos.X - 7f, pos.Y);
                            path.AddLine(pos.X - 7f, pos.Y, pos.X - 10f, pos.Y);
                            path.AddLine(pos.X - 10f, pos.Y, pos.X - 10f, pos.Y + 1f);
                            path.AddLine((float)(pos.X - 10f), (float)(pos.Y + 1f), (float)(pos.X + 10f), (float)(pos.Y + 1f));
                            path.AddLine(pos.X + 10f, pos.Y + 1f, pos.X + 10f, pos.Y);
                            goto Label_0AD7;
                        }
                        if (types == DurationTypes.Whole)
                        {
                            pos = new RawVector2(pos.X - 8f, pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f)));
                            path.AddLine(pos.X - 7f, pos.Y, pos.X + 7f, pos.Y);
                            path.AddLine(pos.X + 7f, pos.Y, pos.X + 7f, pos.Y + 5f);
                            path.AddLine((float)(pos.X + 7f), (float)(pos.Y + 5f), (float)(pos.X - 7f), (float)(pos.Y + 5f));
                            path.AddLine(pos.X - 7f, pos.Y + 5f, pos.X - 7f, pos.Y);
                            path.AddLine(pos.X - 7f, pos.Y, pos.X - 10f, pos.Y);
                            path.AddLine(pos.X - 10f, pos.Y, pos.X - 10f, pos.Y - 1f);
                            path.AddLine((float)(pos.X - 10f), (float)(pos.Y - 1f), (float)(pos.X + 10f), (float)(pos.Y - 1f));
                            path.AddLine(pos.X + 10f, pos.Y - 1f, pos.X + 10f, pos.Y);
                        }
                    }
                    goto Label_0AD7;
                    Label_06F6:
                    pos = new RawVector2(pos.X - 2f, (pos.Y - (6f * (((float)McMeasure.StaveSpacing) / 2f))) + 3f);
                    path.AddLine(pos.X, pos.Y, pos.X + 1.6f, pos.Y);
                    path.AddLine(pos.X + 1.6f, pos.Y, (pos.X - 8f) + 2.4f, pos.Y + 19f);
                    path.AddLine((float)((pos.X - 8f) + 2.4f), (float)(pos.Y + 19f), (float)((pos.X - 8f) - 0.8f), (float)(pos.Y + 19f));
                    path.AddLine((pos.X - 8f) - 0.8f, pos.Y + 19f, pos.X, pos.Y);
                    DrawRestDotPart(renderTarget, pos, color);
                    Label_0AD7:
                    path.Flatten();
                    pathPoints = path.PathPoints;
                    path.Dispose();
                }
                PathGeometry geometry = new PathGeometry(factory2);
                if (pathPoints.Length > 1)
                {
                    GeometrySink sink = geometry.Open();
                    sink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);
                    sink.BeginFigure(new RawVector2(pathPoints[0].X, pathPoints[0].Y), FigureBegin.Filled);
                    for (int i = 1; i < pathPoints.Length; i++)
                    {
                        sink.AddLine(new RawVector2(pathPoints[i].X, pathPoints[i].Y));
                    }
                    sink.EndFigure(FigureEnd.Closed);
                    sink.Close();
                    sink.Dispose();
                }
                SolidColorBrush brush = new SolidColorBrush(renderTarget, color.ToRawColor4(1f));
                renderTarget.FillGeometry(geometry, brush);
                brush.Dispose();
                geometry.Dispose();
                renderTarget.EndDraw();
            }
            catch (Exception)
            {
                factory.Dispose();
                factory2.Dispose();
                factory3.Dispose();
                wicBitmap.Dispose();
                renderTarget.Dispose();
                return(null);
            }
            SharpDX.Direct2D1.Bitmap bitmap2 = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTargetSource, wicBitmap);
            factory.Dispose();
            factory2.Dispose();
            factory3.Dispose();
            wicBitmap.Dispose();
            renderTarget.Dispose();
            return(bitmap2);
        }
예제 #16
0
        public static SharpDX.Direct2D1.Bitmap RedrawMiscNoteBitmapCache(RenderTarget renderTargetSource, Color color)
        {
            ImagingFactory factory = new ImagingFactory();

            SharpDX.Direct2D1.Factory   factory2  = new SharpDX.Direct2D1.Factory();
            SharpDX.DirectWrite.Factory factory3  = new SharpDX.DirectWrite.Factory();
            SharpDX.WIC.Bitmap          wicBitmap = new SharpDX.WIC.Bitmap(factory, 0x10, 0x10, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand);
            RenderTargetProperties      renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Unknown), 0f, 0f, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);
            WicRenderTarget             renderTarget           = new WicRenderTarget(factory2, wicBitmap, renderTargetProperties);

            try
            {
                PointF[] pathPoints;
                renderTarget.BeginDraw();
                renderTarget.Clear(new RawColor4?(Color.Transparent.ToRawColor4(1f)));
                RawVector2 vector = new RawVector2(8f, 8f);
                using (GraphicsPath path = new GraphicsPath())
                {
                    float num  = vector.X - 6f;
                    float num2 = vector.Y - 3f;
                    path.AddLine((float)(num + 0f), (float)(num2 + 0f), (float)(num + 12f), (float)(num2 + 0f));
                    path.AddLine((float)(num + 12f), (float)(num2 + 0f), (float)(num + 12f), (float)(num2 + 6f));
                    path.AddLine((float)(num + 12f), (float)(num2 + 6f), (float)(num + 0f), (float)(num2 + 6f));
                    path.AddLine((float)(num + 0f), (float)(num2 + 6f), (float)(num + 0f), (float)(num2 + 0f));
                    path.Flatten();
                    pathPoints = path.PathPoints;
                    path.Dispose();
                }
                PathGeometry geometry = new PathGeometry(factory2);
                if (pathPoints.Length > 1)
                {
                    GeometrySink sink = geometry.Open();
                    sink.SetSegmentFlags(PathSegment.ForceRoundLineJoin);
                    sink.BeginFigure(new RawVector2(pathPoints[0].X, pathPoints[0].Y), FigureBegin.Filled);
                    for (int i = 1; i < pathPoints.Length; i++)
                    {
                        sink.AddLine(new RawVector2(pathPoints[i].X, pathPoints[i].Y));
                    }
                    sink.EndFigure(FigureEnd.Closed);
                    sink.Close();
                    sink.Dispose();
                }
                SolidColorBrush brush = new SolidColorBrush(renderTarget, color.ToRawColor4(1f));
                renderTarget.FillGeometry(geometry, brush);
                brush.Dispose();
                geometry.Dispose();
                renderTarget.EndDraw();
            }
            catch (Exception)
            {
                factory.Dispose();
                factory2.Dispose();
                factory3.Dispose();
                wicBitmap.Dispose();
                renderTarget.Dispose();
                return(null);
            }
            SharpDX.Direct2D1.Bitmap bitmap2 = SharpDX.Direct2D1.Bitmap.FromWicBitmap(renderTargetSource, wicBitmap);
            factory.Dispose();
            factory2.Dispose();
            factory3.Dispose();
            wicBitmap.Dispose();
            renderTarget.Dispose();
            return(bitmap2);
        }