示例#1
0
        public void Save(Stream systemStream, Direct2DImageFormat format, string text, string faceName, float fontSize, out int width, out int height)
        {
#if BENCHMARK
            using (var handler = Benchmark.Instance.Start("DirectWrite", "Save"))
#endif
            using (var layout = new TextLayout(factoryManager.DwFactory, text, new TextFormat(factoryManager.DwFactory, faceName, fontSize * 1.3f), 4000, 4000))
            {
                width  = (int)Math.Ceiling(layout.Metrics.WidthIncludingTrailingWhitespace);
                height = (int)Math.Ceiling(layout.Metrics.Height);
                using (var wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppPRGBA, BitmapCreateCacheOption.CacheOnLoad))
                {
                    var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default,
                                                                            new SharpDX.Direct2D1.PixelFormat(Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT);
                    using (var renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties))
                        using (var brush = new SolidColorBrush(renderTarget, SharpDX.Color.White))
                            using (var encoder = new BitmapEncoder(factoryManager.WicFactory, Direct2DConverter.ConvertImageFormat(format)))
                            {
                                renderTarget.BeginDraw();
                                renderTarget.Clear(new Color4(1, 1, 1, 0));
                                renderTarget.DrawTextLayout(Vector2.Zero, layout, brush);
                                renderTarget.EndDraw();
                                var stream = new WICStream(factoryManager.WicFactory, systemStream);
                                encoder.Initialize(stream);
                                using (var bitmapFrameEncode = new BitmapFrameEncode(encoder))
                                {
                                    bitmapFrameEncode.Initialize();
                                    bitmapFrameEncode.SetSize(width, height);
                                    bitmapFrameEncode.WriteSource(wicBitmap);
                                    bitmapFrameEncode.Commit();
                                }
                                encoder.Commit();
                            }
                }
            }
        }
 protected override void DrawOntoOutputTarget(WicRenderTarget target)
 {
     foreach (var text in ItemArray)
     {
         var location = ImagePlacement[text.Key];
         var t        = text.Value;
         using (var brush = new SolidColorBrush(target, t.Background))
             target.FillRectangle(location, brush);
         using (var brush = new SolidColorBrush(target, t.Foreground))
             target.DrawTextLayout(new Vector2(location.Left + text.Value.Padding.X, location.Top + text.Value.Padding.Y),
                                   t.TextLayout, brush, DrawTextOptions.None);
     }
 }
示例#3
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());
        }
示例#4
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;
            }
        }