예제 #1
1
        public Button(string pText, float pX, float pY, float pWidth, float pHeight, bool pSmall)
        {
            width = pWidth;
            height = pHeight;
            x = pX;
            y = pY;

            // Text properties
            var brushProp = new LinearGradientBrushProperties();
            brushProp.StartPoint = new Vector2(x, y);
            brushProp.EndPoint = new Vector2(x, y + height);

            var stops = new GradientStop[2];
            stops[0] = new GradientStop() { Color = new Color4(1, 1, 1, 0.5f), Position = 0 };
            stops[1] = new GradientStop() { Color = new Color4(1, 1, 1, 1.0f), Position = 1 };

            textBrush = new LinearGradientBrush(GraphicsWindow.Instance.RenderTarget2D, brushProp, new GradientStopCollection(GraphicsWindow.Instance.RenderTarget2D, stops));
            textLayout = new TextLayout(Factories.FactoryWrite, pText, pSmall? Constants.SmallFont : Constants.RegularFont, width, height);

            // Frame properties
            borderBrush = new SolidColorBrush(GraphicsWindow.Instance.RenderTarget2D, new Color4(0, 0, 0, 0.3f));
            backBrush = new SolidColorBrush(GraphicsWindow.Instance.RenderTarget2D, new Color4(0.1f, 0.3f, 0.4f, 0.5f));
            highlightBrush = new SolidColorBrush(GraphicsWindow.Instance.RenderTarget2D, new Color4(0.2f, 0.6f, 0.8f, 0.5f));
            highlight = false;
        }
예제 #2
1
파일: Program.cs 프로젝트: Nezz/SharpDX
        protected override void Initialize(DemoConfiguration demoConfiguration)
        {
            base.Initialize(demoConfiguration);

            // Initialize a TextFormat
            TextFormat = new TextFormat(FactoryDWrite, "Calibri", 128) {TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center};

            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            // Initialize a TextLayout
            TextLayout = new TextLayout(FactoryDWrite, "SharpDX D2D1 - DWrite", TextFormat, demoConfiguration.Width, demoConfiguration.Height);
        }
예제 #3
0
 public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, BaseBrush brush = null)
 {
     var layout = new DW.TextLayout(factories.DWFactory, text, GetTextFormat(font), (float)frame.Width, (float)frame.Height);
     var h      = layout.Metrics.Height;
     //todo : : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
     //renderTarget.DrawTextLayout ((frame.TopLeft - h*Point.OneY.Y).ToVector2 (), layout, GetBrush (frame, brush));
 }
예제 #4
0
 public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
 {
     try
     {
         if (brush == null)
         {
             brush = new SolidBrush(Color.FromRGB(0, 0, 0, 0));
         }
         var layout = new DW.TextLayout(factories.DWFactory, text, WinUniversalPlatform.GetTextFormat(factories, font), (float)frame.Width, (float)frame.Height);
         var h      = layout.Metrics.Height + layout.OverhangMetrics.Top;
         var point  = (frame.TopLeft - h * Point.OneY).ToVector2();
         if (pen == null)
         {
             renderTarget.DrawTextLayout(point, layout, GetBrush(frame, brush));
         }
         else
         {
             using (var pentr = new TextRendererWithPen(factories.D2DFactory, renderTarget))
             {
                 pentr.PenBrush  = GetBrush(pen);
                 pentr.PenWidth  = (float)pen.Width;
                 pentr.PenStyle  = GetStrokeStyle(pen);
                 pentr.FontBrush = GetBrush(frame, brush);
                 layout.Draw(pentr, point.X, point.Y);
             }
         }
     }
     catch
     {
         System.Diagnostics.Debug.WriteLine("drawtexterror");
     }
 }
예제 #5
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight,
            TextWrapping wrapping)
        {
            var factory = AvaloniaLocator.Current.GetService<DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize))
            {
                format.WordWrapping = wrapping == TextWrapping.Wrap ? 
                    DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    float.MaxValue,
                    float.MaxValue);
            }

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
예제 #6
0
        /// <inheritdoc />
        public override void Layout()
        {
            base.Layout();

            this.textLayout?.Dispose();
            this.textLayout = new DWrite.TextLayout(this.dwriteFactory, this.text, this.textFormat, this.Size.Width, this.Size.Height);
        }
        public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
        {
            var layout = new DW.TextLayout(factories.DWFactory, text, GetTextFormat(font), (float)frame.Width, (float)frame.Height);
            var h      = layout.Metrics.Height;

            renderTarget.DrawTextLayout((frame.TopLeft - h * Point.OneY).ToVector2(), layout, GetBrush(frame, brush));
        }
예제 #8
0
            public TextLayoutParameters(
                DWrite.Factory factory,
                string name,
                float pointSize,
                bool bold,
                bool italic,
                bool underline,
                bool strikeout,
                Size2F dpi)
            {
                this.FontName  = name;
                this.PointSize = pointSize;
                this.DipSize   = Helpers.GetFontSize(pointSize);
                this.Weight    = bold ? DWrite.FontWeight.Bold : DWrite.FontWeight.Normal;
                this.Style     = italic ? DWrite.FontStyle.Italic : DWrite.FontStyle.Normal;
                this.Underline = underline;
                this.StrikeOut = strikeout;

                using (var textFormat = new DWrite.TextFormat(factory, this.FontName, this.Weight, this.Style, this.DipSize))
                    using (var textLayout = new DWrite.TextLayout(factory, "A", textFormat, 1000, 1000))
                    {
                        this.LineHeight = Helpers.AlignToPixel(textLayout.Metrics.Height, dpi.Height);
                        this.CharWidth  = Helpers.AlignToPixel(textLayout.OverhangMetrics.Left + (1000 + textLayout.OverhangMetrics.Right), dpi.Width);
                    }
            }
예제 #9
0
        static sw.TextLayout GetTextLayout(Font font, string text)
        {
            var fontHandler = (FontHandler)font.Handler;
            var textLayout  = new sw.TextLayout(SDFactory.DirectWriteFactory, text, fontHandler.TextFormat, float.MaxValue, float.MaxValue);

            return(textLayout);
        }
예제 #10
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            var factory = PerspexLocator.Current.GetService <DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                       factory,
                       fontFamily,
                       (DWrite.FontWeight)fontWeight,
                       (DWrite.FontStyle)fontStyle,
                       (float)fontSize))
            {
                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    float.MaxValue,
                    float.MaxValue);
            }

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
예제 #11
0
        public static void WriteChat(D2D.WindowRenderTarget renderTarget, Starbase starbase, SharpDX.DirectWrite.Factory textFactory, TextFormat textFormat, float height, D2D.Brush brush)
        {
            renderTarget.Clear(new SharpDX.Mathematics.Interop.RawColor4(0f, 0f, 0f, 0f));

            lock (starbase.SyncMessages)
            {
                int number     = starbase.Messages.Count;
                int offset     = 0;
                int showNumber = number - 10 < 0 ? 0 : number - 10;
                int maxNumber  = number - showNumber < 10 ? number - showNumber : 10;

                if (number > 0)
                {
                    foreach (string message in starbase.Messages.GetRange(showNumber, maxNumber))
                    {
                        using (SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(textFactory, message, textFormat, 500, 500))
                            renderTarget.DrawTextLayout(new SharpDX.Mathematics.Interop.RawVector2()
                            {
                                X = 10, Y = height - 110 + offset
                            }, layout, brush, D2D.DrawTextOptions.Clip);

                        offset += 10;
                    }
                }
            }
        }
예제 #12
0
        public TextLayout GetLayout()
        {
            if(mAlignmentChanged)
            {
                if (mLayout != null)
                {
                    mLayout.TextAlignment = mHorizontalAlignment;
                    mLayout.ParagraphAlignment = mVerticalAlignment;
                }
                mAlignmentChanged = false;
            }

            if (mChanged == false)
                return mLayout;

            var font = Fonts.Cache[mFontFamily, mFontSize, mWeight];

            if (mLayout != null)
                mLayout.Dispose();
            mLayout = new TextLayout(mFactory, mText, font, mSize.Width,
                mSize.Height)
            {
                TextAlignment = mHorizontalAlignment,
                ParagraphAlignment = mVerticalAlignment,
            };

            mChanged = false;
            mAlignmentChanged = false;
            return mLayout;
        }
예제 #13
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight,
            TextWrapping wrapping)
        {
            var factory = AvaloniaLocator.Current.GetService <DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                       factory,
                       fontFamily,
                       (DWrite.FontWeight)fontWeight,
                       (DWrite.FontStyle)fontStyle,
                       (float)fontSize))
            {
                format.WordWrapping = wrapping == TextWrapping.Wrap ?
                                      DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    float.MaxValue,
                    float.MaxValue);
            }

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
예제 #14
0
        public FormattedTextImpl(
            string text,
            string fontFamily,
            double fontSize,
            FontStyle fontStyle,
            TextAlignment textAlignment,
            FontWeight fontWeight)
        {
            var factory = Locator.Current.GetService<DWrite.Factory>();

            var format = new DWrite.TextFormat(
                factory,
                fontFamily,
                (DWrite.FontWeight)fontWeight,
                (DWrite.FontStyle)fontStyle,
                (float)fontSize);

            TextLayout = new DWrite.TextLayout(
                factory,
                text ?? string.Empty,
                format,
                float.MaxValue,
                float.MaxValue);

            TextLayout.TextAlignment = textAlignment.ToDirect2D();
        }
예제 #15
0
        public System.Drawing.SizeF MeasureString(string Message, TextFormat textFormat, float Width, ContentAlignment Align = ContentAlignment.MiddleLeft)
        {
            SharpDX.DirectWrite.TextLayout layout =
                new SharpDX.DirectWrite.TextLayout(_FactoryDWrite, Message, textFormat, Width, textFormat.FontSize);

            return(new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height));
        }
예제 #16
0
        private bool Ekranabas(SharpDX.Vector2 ekran, string yazi, System.Drawing.Color renk, TextFormat qfont)
        {
            TextLayout TL = new SharpDX.DirectWrite.TextLayout(fontFactory, yazi, qfont, float.MaxValue, float.MaxValue);

            device.DrawTextLayout(ekran, TL, (new SolidColorBrush(device, RawColorFromColor(renk))), DrawTextOptions.NoSnap);
            TL.Dispose();
            return(true);
        }
        public Size MeasureText(string text, Font font)
        {
            float maxWidth  = float.MaxValue;
            float maxHeight = float.MaxValue;
            var   layout    = new DW.TextLayout(factories.DWFactory, text, GetTextFormat(font), maxWidth, maxHeight);

            return(new Size(layout.Metrics.Width, layout.Metrics.Height));
        }
예제 #18
0
        /// <summary>
        /// If the properties have once been set, only change the important variables.
        /// </summary>
        /// <param name="Menu_Text_Array"></param>
        /// <param name="Window_Position_X"></param>
        /// <param name="Window_Position_Y"></param>
        /// <param name="DirectX_Graphics_Device"></param>
        /// <param name="Drawing_Properties"></param>
        /// <param name="Sonic_Heroes_Overlay"></param>
        public static Menu_Base.DirectX_2D_Overlay_Properties Adjust_Menu_Width(string[] Menu_Text_Array, float Window_Position_X, float Window_Position_Y, WindowRenderTarget DirectX_Graphics_Device, Form Windows_Forms_Fake_Transparent_Overlay, Menu_Base.DirectX_2D_Overlay_Properties Current_Drawing_Properties)
        {
            try
            {
                // Obtain TextLayout in order to obtain text width and height properties.
                SharpDX.DirectWrite.TextLayout[] All_Text_Layouts = new SharpDX.DirectWrite.TextLayout[Menu_Text_Array.Length]; // Get all text layout info
                for (int x = 0; x < Menu_Text_Array.Length; x++)
                {
                    All_Text_Layouts[x] = new TextLayout(new SharpDX.DirectWrite.Factory(), Menu_Text_Array[x], DirectX_2D_Overlay_Properties.Text_Font_DirectX, float.PositiveInfinity, float.PositiveInfinity);
                }

                // Obtain Largest Width and Height
                float Rectangle_Background_Width = All_Text_Layouts[0].Metrics.Width;
                for (int x = 1; x < All_Text_Layouts.Length; x++)
                {
                    if (All_Text_Layouts[x].Metrics.Width > Rectangle_Background_Width)
                    {
                        Rectangle_Background_Width = All_Text_Layouts[x].Metrics.Width;
                    }
                }


                // Make Rectangle Bigger (Styling)
                Rectangle_Background_Width += (Current_Drawing_Properties.Line_Spacing * 2);

                // Obtain X position across the form for the selected location of item.
                int Window_Position_X_Local = (int)(((Windows_Forms_Fake_Transparent_Overlay.Width / 100.0F) * Window_Position_X));

                // Get horizontal location of rectangle
                int Rectangle_Location_X = Window_Position_X_Local - (int)(Rectangle_Background_Width / 2.0F);

                // If the right edge will escape the screen, make sure it does not.
                if ((Rectangle_Background_Width + Rectangle_Location_X) > Windows_Forms_Fake_Transparent_Overlay.Width)
                {
                    int Menu_Overflow_Pixels = ((int)Rectangle_Background_Width + Rectangle_Location_X) - Windows_Forms_Fake_Transparent_Overlay.Width; // Get the amount of pixels rectangle escapes of screen.
                    Rectangle_Location_X = Rectangle_Location_X - Menu_Overflow_Pixels;                                                                 // Move the rectangle by the overflow amount.
                }

                // Check for top and left edges of overlay if they escape the view.
                if (Rectangle_Location_X < 0)
                {
                    Rectangle_Location_X = 0;
                }

                // Define Background Rectangle
                Current_Drawing_Properties.Rectangle_Menu_DirectX.X      = Rectangle_Location_X;
                Current_Drawing_Properties.Rectangle_Menu_DirectX.Width  = (int)Rectangle_Background_Width;
                Current_Drawing_Properties.Rectangle_Title_DirectX.X     = Rectangle_Location_X;
                Current_Drawing_Properties.Rectangle_Title_DirectX.Width = (int)Rectangle_Background_Width;

                return(Current_Drawing_Properties);
            } catch (Exception Ex)
            {
                Program.Sonic_Heroes_Networking_Client.SendData_Alternate(Message_Type.Client_Call_Send_Message, Encoding.ASCII.GetBytes("[Debug] Tweakbox | " + Ex.Message + " | " + Ex.StackTrace + " | If you see this, you should report this back to me."), false);
                return(new Menu_Base.DirectX_2D_Overlay_Properties());
            }
        }
예제 #19
0
        /// <summary>
        /// Builds the text geometry for the given string.
        /// </summary>
        /// <param name="stringToBuild">The string to build within the geometry.</param>
        /// <param name="geometryOptions">Some configuration for geometry creation.</param>
        public void BuildTextGeometry(string stringToBuild, TextGeometryOptions geometryOptions)
        {
            DWrite.Factory writeFactory = GraphicsCore.Current.FactoryDWrite;

            //TODO: Cache font objects

            //Get DirectWrite font weight
            DWrite.FontWeight fontWeight = DWrite.FontWeight.Normal;
            switch (geometryOptions.FontWeight)
            {
            case FontGeometryWeight.Bold:
                fontWeight = DWrite.FontWeight.Bold;
                break;

            default:
                fontWeight = DWrite.FontWeight.Normal;
                break;
            }

            //Get DirectWrite font style
            DWrite.FontStyle fontStyle = DWrite.FontStyle.Normal;
            switch (geometryOptions.FontStyle)
            {
            case FontGeometryStyle.Italic:
                fontStyle = DWrite.FontStyle.Italic;
                break;

            case FontGeometryStyle.Oblique:
                fontStyle = DWrite.FontStyle.Oblique;
                break;

            default:
                fontStyle = DWrite.FontStyle.Normal;
                break;
            }

            //Create the text layout object
            try
            {
                DWrite.TextLayout textLayout = new DWrite.TextLayout(
                    writeFactory, stringToBuild,
                    new DWrite.TextFormat(
                        writeFactory, geometryOptions.FontFamily, fontWeight, fontStyle, geometryOptions.FontSize),
                    float.MaxValue, float.MaxValue, 1f, true);

                //Render the text using the vertex structure text renderer
                using (VertexStructureTextRenderer textRenderer = new VertexStructureTextRenderer(this, geometryOptions))
                {
                    textLayout.Draw(textRenderer, 0f, 0f);
                }
            }
            catch (SharpDX.SharpDXException)
            {
                //TODO: Display some error
            }
        }
예제 #20
0
        /// <inheritdoc />
        public override void Layout()
        {
            base.Layout();

            this.textLayout?.Dispose();

            var width = this.Size.Width - (PaddingHorizontal * 2);

            this.textLayout = new DWrite.TextLayout(this.dwriteFactory, this.text, this.textFormat, width <= 0 ? 1 : width, this.Size.Height);
        }
예제 #21
0
        DW.TextLayout createTextLayout(string text, DW.TextFormat format, double width, double height)
        {
            var layout = new DW.TextLayout(requireWriteFactory(), text, format, width.import(), height.import());

            layout.TextAlignment      = _state.TextAlignment.import();
            layout.ParagraphAlignment = _state.ParagraphAlignment.import();
            layout.WordWrapping       = _state.WordWrapping.import();

            return(layout);
        }
예제 #22
0
        DW.TextLayout createTextLayout(string text, DW.TextFormat format, double width, double height)
        {
            var layout = new DW.TextLayout(requireWriteFactory(), text, format, width.import(), height.import())
            {
                TextAlignment = _state.TextAlignment.import(),
                ParagraphAlignment = _state.ParagraphAlignment.import(),
                WordWrapping = _state.WordWrapping.import()
            };

            return layout;
        }
예제 #23
0
        public void DrawString(string s, float x, float y, float width, float height, LineBreakMode lineBreak, TextAlignment align)
        {
            if (this.font != null)
            {
                var textFormat = this.font.Tag as DW.TextFormat;
                using (var layout = new SharpDX.DirectWrite.TextLayout(dwFactory, s, textFormat, width, height))
                {
                    DrawTextOptions drawTextOptions;
                    switch (lineBreak)
                    {
                    case LineBreakMode.None:
                        drawTextOptions = DrawTextOptions.None;
                        break;

                    case LineBreakMode.Clip:
                        drawTextOptions = DrawTextOptions.Clip;
                        break;

                    case LineBreakMode.WordWrap:
                        drawTextOptions     = DrawTextOptions.None;
                        layout.WordWrapping = SharpDX.DirectWrite.WordWrapping.Wrap;
                        break;

                    default:
                        drawTextOptions = DrawTextOptions.None;
                        break;
                    }
                    switch (align)
                    {
                    case TextAlignment.Left:
                        layout.TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading;
                        break;

                    case TextAlignment.Center:
                        layout.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center;
                        break;

                    case TextAlignment.Right:
                        layout.TextAlignment = SharpDX.DirectWrite.TextAlignment.Trailing;
                        break;

                    case TextAlignment.Justified:
                        // Needs Windows 8
                        break;

                    default:
                        break;
                    }

                    dc.DrawTextLayout(new Vector2(x, y), layout, lastBrush, drawTextOptions);
                }
            }
        }
예제 #24
0
        public static TextMetrics GlobalMeasureText(Direct2DFactories factories, string text, Font font)
        {
            float maxWidth  = float.MaxValue;
            float maxHeight = float.MaxValue;
            var   layout    = new DW.TextLayout(factories.DWFactory, text, GetTextFormat(factories, font), maxWidth, maxHeight);

            return(new TextMetrics
            {
                Width = layout.Metrics.Width,
                Ascent = layout.Metrics.Height + layout.OverhangMetrics.Top,
                Descent = -layout.OverhangMetrics.Top,
            });
        }
예제 #25
0
 private void DrawText(string text, float locX, float locY, D2D1.Brush fg, D2D1.Brush bg, string font = "", float size = 0)
 {
     using (TextFormat = new DW.TextFormat(DWFactory, font == "" ? Config.CooldownBarTextFont : font, size == 0 ? Config.CooldownBarTextFontSize : size)) {
         TextFormat.WordWrapping = DW.WordWrapping.NoWrap;
         using (DW.TextLayout TextLayout = new DW.TextLayout(DWFactory, text, TextFormat, 500, 500)) {
             using (TextBrush = new TextBrush(fg, bg)) {
                 using (TextRenderer = new TextRenderer(Render, TextBrush)) {
                     TextLayout.SetDrawingEffect(TextBrush, new DW.TextRange(10, 20));
                     TextLayout.Draw(TextRenderer, locX, locY);
                 }
             }
         }
     }
 }
예제 #26
0
        public D2D.GeometryRealization CreateSymbol(ShowSymbol sym, DW.TextFormat format)
        {
            D2D.GeometryRealization cached_geo = null;
            bool result = symbol_cache.TryGetValue(sym, out cached_geo);

            if (!result)
            {
                const int        margin = 2;
                D2D.Geometry     geo    = null;
                DW.TextLayout    layout = null;
                D2D.PathGeometry path   = null;
                DW.TextMetrics   metrics;
                D2D.StrokeStyle  stroke = null;
                switch (sym)
                {
                case ShowSymbol.FullSpace:
                    layout  = new DW.TextLayout(this._DWFactory, " ", format, float.MaxValue, float.MaxValue);
                    metrics = layout.Metrics;
                    Rectangle rect = new Rectangle(margin, margin, Math.Max(1, metrics.WidthIncludingTrailingWhitespace - margin * 2), Math.Max(1, metrics.Height - margin * 2));
                    geo    = new D2D.RectangleGeometry(this.Factory, rect);
                    stroke = this.GetStroke(HilightType.Dash);
                    break;

                case ShowSymbol.HalfSpace:
                    layout  = new DW.TextLayout(this._DWFactory, " ", format, float.MaxValue, float.MaxValue);
                    metrics = layout.Metrics;
                    rect    = new Rectangle(margin, margin, Math.Max(1, metrics.WidthIncludingTrailingWhitespace - margin * 2), Math.Max(1, metrics.Height - margin * 2));
                    geo     = new D2D.RectangleGeometry(this.Factory, rect);
                    stroke  = this.GetStroke(HilightType.Sold);
                    break;

                case ShowSymbol.Tab:
                    layout  = new DW.TextLayout(this._DWFactory, "0", format, float.MaxValue, float.MaxValue);
                    metrics = layout.Metrics;
                    path    = new D2D.PathGeometry(this.Factory);
                    var sink = path.Open();
                    sink.BeginFigure(new SharpDX.Mathematics.Interop.RawVector2(1, 1), D2D.FigureBegin.Filled);     //少し隙間を開けないと描写されない
                    sink.AddLine(new SharpDX.Mathematics.Interop.RawVector2((float)1, (float)metrics.Height));
                    sink.EndFigure(D2D.FigureEnd.Closed);
                    sink.Close();
                    geo    = path;
                    stroke = this.GetStroke(HilightType.Sold);
                    break;
                }
                cached_geo = new D2D.GeometryRealization(this.Device, geo, 1.0f, 1.0f, stroke);
                this.symbol_cache.Add(sym, cached_geo);
            }
            return(cached_geo);
        }
예제 #27
0
        public static sw.TextLayout GetTextLayout(Font font, string text)
        {
            var fontHandler = (FontHandler)font.Handler;
            var textLayout  = new sw.TextLayout(SDFactory.DirectWriteFactory, text, fontHandler.TextFormat, float.MaxValue, float.MaxValue);

            if (font.Strikethrough)
            {
                textLayout.SetStrikethrough(true, new sw.TextRange(0, text.Length));
            }
            if (font.Underline)
            {
                textLayout.SetUnderline(true, new sw.TextRange(0, text.Length));
            }
            return(textLayout);
        }
예제 #28
0
        public DWrite.TextLayout this[string text, float fontSize, string fontFamilyName = "Consolas"]
        {
            get
            {
                var key = $"{text}:{fontSize}";
                if (!_bmps.ContainsKey(key))
                {
                    _bmps[key] = new DWrite.TextLayout(_dwriteFactory,
                                                       text,
                                                       _textManager[fontSize, fontFamilyName],
                                                       float.MaxValue, fontSize * 2.0f);
                }

                return(_bmps[key]);
            }
        }
예제 #29
0
        protected override void Initialize(GameConfiguration gameConfiguration)
        {
            base.Initialize(gameConfiguration);            // Initialize a TextFormat

            Components.Add(ScreenManager = new ScreenManager(this));
            ScreenManager.ToggleScreen(new GameScreen(this));

            // Initialize a TextFormat
            TextFormat = new TextFormat(FactoryDWrite, "微软雅黑", 128) { TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center };

            RenderTarget2D.TextAntialiasMode = TextAntialiasMode.Cleartype;

            // Initialize a TextLayout
            TextLayout = new TextLayout(FactoryDWrite, "编程棋 Alpha 0", TextFormat, gameConfiguration.Width, gameConfiguration.Height);

        }
예제 #30
0
        public FormattedTextImpl(
            string text,
            Typeface typeface,
            double fontSize,
            TextAlignment textAlignment,
            TextWrapping wrapping,
            Size constraint,
            IReadOnlyList <FormattedTextStyleSpan> spans)
        {
            Text = text;

            var font       = ((GlyphTypefaceImpl)typeface.GlyphTypeface.PlatformImpl).DWFont;
            var familyName = font.FontFamily.FamilyNames.GetString(0);

            using (var textFormat = new DWrite.TextFormat(
                       Direct2D1Platform.DirectWriteFactory,
                       familyName,
                       font.FontFamily.FontCollection,
                       (DWrite.FontWeight)typeface.Weight,
                       (DWrite.FontStyle)typeface.Style,
                       DWrite.FontStretch.Normal,
                       (float)fontSize))
            {
                textFormat.WordWrapping =
                    wrapping == TextWrapping.Wrap ? DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    Direct2D1Platform.DirectWriteFactory,
                    Text ?? string.Empty,
                    textFormat,
                    (float)constraint.Width,
                    (float)constraint.Height)
                {
                    TextAlignment = textAlignment.ToDirect2D()
                };
            }

            if (spans != null)
            {
                foreach (var span in spans)
                {
                    ApplySpan(span);
                }
            }

            Bounds = Measure();
        }
예제 #31
0
        private static float CalcBaselineOffset(DW.TextLayout tl, DominantBaseline db)
        {
            var lm = tl.GetLineMetrics()[0];

            switch (db)
            {
            case DominantBaseline.Middle:
                return((lm.Height + (lm.Height - lm.Baseline)) / 2);

            case DominantBaseline.Auto:
            case DominantBaseline.Baseline:
                return(lm.Baseline);

            default:
                return(lm.Height - lm.Baseline);
            }
        }
예제 #32
0
        public Title(string pText, float pX, float pY)
        {
            width = Constants.Width - 2 * pX;
            height = 70;
            x = pX;
            y = pY;

            var brushProp = new LinearGradientBrushProperties();
            brushProp.StartPoint = new Vector2(x, y);
            brushProp.EndPoint = new Vector2(x, y + height);

            var stops = new GradientStop[2];
            stops[0] = new GradientStop() { Color = new Color4(0.1f, 0.3f, 0.4f, 0.5f), Position = 0 };
            stops[1] = new GradientStop() { Color = new Color4(0.1f, 0.3f, 0.4f, 0.5f), Position = 1 };

            brush = new LinearGradientBrush(GraphicsWindow.Instance.RenderTarget2D, brushProp, new GradientStopCollection(GraphicsWindow.Instance.RenderTarget2D, stops));
            textLayout = new TextLayout(Factories.FactoryWrite, pText, Constants.BoldFont, width, height);
        }
        public FormattedTextImpl(
            string text,
            Typeface typeface,
            TextAlignment textAlignment,
            TextWrapping wrapping,
            Size constraint,
            IReadOnlyList <FormattedTextStyleSpan> spans)
        {
            Text = text;
            var factory = AvaloniaLocator.Current.GetService <DWrite.Factory>();

            using (var format = new DWrite.TextFormat(
                       factory,
                       typeface?.FontFamilyName ?? "Courier New",
                       (DWrite.FontWeight)(typeface?.Weight ?? FontWeight.Normal),
                       (DWrite.FontStyle)(typeface?.Style ?? FontStyle.Normal),
                       (float)(typeface?.FontSize ?? 12)))
            {
                format.WordWrapping = wrapping == TextWrapping.Wrap ?
                                      DWrite.WordWrapping.Wrap :
                                      DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    factory,
                    text ?? string.Empty,
                    format,
                    (float)constraint.Width,
                    (float)constraint.Height)
                {
                    TextAlignment = textAlignment.ToDirect2D()
                };
            }

            if (spans != null)
            {
                foreach (var span in spans)
                {
                    ApplySpan(span);
                }
            }

            Size = Measure();
        }
예제 #34
0
 protected void UpdateInputTextLayout()
 {
     if (InputText?.IsEmpty() ?? true)
     {
         InputTextLayout = null;
     }
     else
     {
         var textLayout = new DW.TextLayout(DwFactory, InputText, InputTextFormat, 0, 0);
         if (HintText != null)
         {
             var len = Math.Min(InputText.Length, HintText.Length);
             for (var i = 0; i < len; i++)
             {
                 var brush = InputText[i] == HintText[i] ? CorrectColorBrush : WrongColorBrush;
                 textLayout.SetDrawingEffect(brush, new DW.TextRange(i, 1));
             }
         }
         InputTextLayout = textLayout;
     }
 }
예제 #35
0
        public FormattedTextImpl(
            string text,
            Typeface typeface,
            TextAlignment textAlignment,
            TextWrapping wrapping,
            Size constraint,
            IReadOnlyList <FormattedTextStyleSpan> spans)
        {
            Text = text;

            var factory = AvaloniaLocator.Current.GetService <DWrite.Factory>();

            var textFormat = Direct2D1FontCollectionCache.GetTextFormat(typeface);

            textFormat.WordWrapping =
                wrapping == TextWrapping.Wrap ? DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

            TextLayout = new DWrite.TextLayout(
                factory,
                Text ?? string.Empty,
                textFormat,
                (float)constraint.Width,
                (float)constraint.Height)
            {
                TextAlignment = textAlignment.ToDirect2D()
            };

            textFormat.Dispose();

            if (spans != null)
            {
                foreach (var span in spans)
                {
                    ApplySpan(span);
                }
            }

            Size = Measure();
        }
예제 #36
0
        public override void DrawText(string str, gdi.Color color, float x, float y, string fontFamily, float size, TextAlign align)
        {
            using (SolidColorBrush b = new SolidColorBrush(renderTarget,
                                                           new RawColor4(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f)))
            {
                using (text.TextFormat format = new text.TextFormat(writeFactory, fontFamily, Util.MmToPoint(size)))
                {
                    switch (align)
                    {
                    case TextAlign.Left: format.TextAlignment = text.TextAlignment.Leading; break;

                    case TextAlign.Center: format.TextAlignment = text.TextAlignment.Center; break;

                    case TextAlign.Right: format.TextAlignment = text.TextAlignment.Trailing; break;
                    }
                    using (text.TextLayout layout = new text.TextLayout(writeFactory, str, format, 1000, 1000, Util.GetScaleFactor(), true))
                    {
                        layout.MaxWidth = layout.Metrics.Width;
                        renderTarget.DrawTextLayout(new RawVector2(x, y), layout, b);
                    }
                }
            }
        }
예제 #37
0
        public DW.TextLayout GetTextLayout(Text.Font font, string text, float maxWidth)
        {
            var tl = new DW.TextLayout(
                _factory,
                text,
                GetTextFormat(font),
                maxWidth,
                9999999
                );

            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (font.TextDecoration)
            {
            case TextDecoration.LineThrough:
                tl.SetStrikethrough(true, new DW.TextRange(0, text.Length));
                break;

            case TextDecoration.Underline:
                tl.SetUnderline(true, new DW.TextRange(0, text.Length));
                break;
            }

            return(tl);
        }
예제 #38
0
        public FormattedTextImpl(
            string text,
            Typeface typeface,
            TextAlignment textAlignment,
            TextWrapping wrapping,
            Size constraint,
            IReadOnlyList <FormattedTextStyleSpan> spans)
        {
            Text = text;

            using (var textFormat = Direct2D1FontCollectionCache.GetTextFormat(typeface))
            {
                textFormat.WordWrapping =
                    wrapping == TextWrapping.Wrap ? DWrite.WordWrapping.Wrap : DWrite.WordWrapping.NoWrap;

                TextLayout = new DWrite.TextLayout(
                    Direct2D1Platform.DirectWriteFactory,
                    Text ?? string.Empty,
                    textFormat,
                    (float)constraint.Width,
                    (float)constraint.Height)
                {
                    TextAlignment = textAlignment.ToDirect2D()
                };
            }

            if (spans != null)
            {
                foreach (var span in spans)
                {
                    ApplySpan(span);
                }
            }

            Bounds = Measure();
        }
예제 #39
0
 public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
 {
     var layout = new DW.TextLayout (factories.DWFactory, text, GetTextFormat (font), (float)frame.Width, (float)frame.Height);
     var h = layout.Metrics.Height;
     renderTarget.DrawTextLayout ((frame.TopLeft - h*Point.OneY).ToVector2 (), layout, GetBrush (frame, brush));
 }
예제 #40
0
        /// <summary>
        /// Updates the TextFormat and TextLayout.
        /// </summary>
        private void UpdateTextFormatAndLayout()
        {
            try
            {
                if (CurrentTextFormat != null)
                {
                    CurrentTextFormat.Release();
                    CurrentTextFormat = null;
                }

                if (CurrentTextLayout != null)
                {
                    CurrentTextLayout.Release();
                    CurrentTextLayout = null;
                }

                // Initialize a TextFormat
                CurrentTextFormat = new TextFormat(FactoryDWrite, FontFamilyName, FontSize) { TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center };

                CurrentTextLayout = new TextLayout(FactoryDWrite, FontText, CurrentTextFormat, renderControl.Width, renderControl.Height);

                // Set a stylistic typography
                var typo = new Typography(FactoryDWrite);
                typo.AddFontFeature(new FontFeature(FontFeatureTag.StylisticSet7, 1));
                CurrentTextLayout.SetTypography(typo, CurrentTextRange);
                typo.Release();

                UpdateBold();
                UpdateItalic();
                UpdateUnderline();
                UpdateFontSize();
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
예제 #41
0
 public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, BaseBrush brush = null)
 {
     var layout = new DW.TextLayout (factories.DWFactory, text, GetTextFormat (font), (float)frame.Width, (float)frame.Height);
     var h = layout.Metrics.Height;
       //todo : : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
       //renderTarget.DrawTextLayout ((frame.TopLeft - h*Point.OneY.Y).ToVector2 (), layout, GetBrush (frame, brush));
 }
        /// <summary>
        /// Inits the font family names from DirectWrite
        /// </summary>
        private void InitTextFormatLayout()
        {
            FontFamilyName = "Gabriola";
            FontSize = 72;
            FontText = "Client Drawing Effect Example!";

            // Initialize a TextFormat
            CurrentTextFormat = new TextFormat(FactoryDWrite, FontFamilyName, FontSize) { TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center };

            CurrentTextLayout = new TextLayout(FactoryDWrite, FontText, CurrentTextFormat, ClientRectangle.Width, ClientRectangle.Height);

            RedDrawingeffect = new ColorDrawingEffect(new Color4(1, 1, 0, 0));
            BlueDrawingEffect = new ColorDrawingEffect(new Color4(1, 0, 0, 1));
            GreenDrawingEffect = new ColorDrawingEffect(new Color4(1, 0, 1, 0));

            CurrentTextLayout.SetDrawingEffect(RedDrawingeffect, new TextRange(0, 14));
            CurrentTextLayout.SetDrawingEffect(BlueDrawingEffect, new TextRange(14, 7));
            CurrentTextLayout.SetDrawingEffect(GreenDrawingEffect, new TextRange(21, 8));

            // Set a stylistic typography
            var typo = new Typography(FactoryDWrite);
            typo.AddFontFeature(new FontFeature(FontFeatureTag.StylisticSet7, 1));
            CurrentTextLayout.SetTypography(typo, CurrentTextRange);
            typo.Release();
        }
        public void DrawText(string text, int font, int brush, float x, float y, bool bufferText = true)
        {
            if (bufferText)
            {
                var bufferPos = -1;

                for (var i = 0; i < _layoutContainer.Count; i++)
                {
                    if (_layoutContainer[i].Text.Length != text.Length || _layoutContainer[i].Text != text) continue;
                    bufferPos = i;
                    break;
                }

                if (bufferPos == -1)
                {
                    _layoutContainer.Add(new LayoutBuffer(text, new TextLayout(_fontFactory, text, _fontContainer[font], float.MaxValue, float.MaxValue)));
                    bufferPos = _layoutContainer.Count - 1;
                }

                _device.DrawTextLayout(new RawVector2(x, y), _layoutContainer[bufferPos].TextLayout, _brushContainer[brush], DrawTextOptions.NoSnap);
            }
            else
            {
                var layout = new TextLayout(_fontFactory, text, _fontContainer[font], float.MaxValue, float.MaxValue);
                _device.DrawTextLayout(new RawVector2(x, y), layout, _brushContainer[brush]);
                layout.Dispose();
            }
        }
예제 #44
0
        private CCSize GetMeasureString(string text)
        {

            var textLayout = new TextLayout(FactoryDWrite, text, textFormat, 2048, 2048);
            var tlMetrics = textLayout.Metrics;

            return new CCSize(tlMetrics.Width, tlMetrics.Height);
        }
 public Line(Brush color, TextLayout text)
 {
     this.TextColor = color;
     this.Text = text;
 }
예제 #46
0
 /// <summary>	
 /// Draws the formatted text described by the specified <see cref="T:SharpDX.DirectWrite.TextLayout" /> object.	
 /// </summary>	
 /// <remarks>	
 /// When drawing the same text repeatedly, using the DrawTextLayout method is more efficient than using the {{DrawText}} method because the text doesn't need to be formatted and the layout processed with each call. This method doesn't return an error code if it fails. To determine whether a drawing operation (such as DrawTextLayout) failed, check the result returned by the <see cref="M:SharpDX.Direct2D1.RenderTarget.EndDraw(System.Int64@,System.Int64@)" /> or <see cref="M:SharpDX.Direct2D1.RenderTarget.Flush(System.Int64@,System.Int64@)" /> methods.  	
 /// </remarks>	
 /// <param name="origin">The point, described in device-independent pixels, at which the upper-left corner of the text described by textLayout is drawn. </param>
 /// <param name="textLayout">The formatted text to draw. Any drawing effects that do not inherit from <see cref="T:SharpDX.Direct2D1.Resource" /> are ignored. If there are drawing effects that inherit from ID2D1Resource that are not brushes, this method fails and the render target is put in an error state.  </param>
 /// <param name="defaultForegroundBrush">The brush used to paint any text in textLayout that does not already have a brush associated with it as a drawing effect (specified by the <see cref="M:SharpDX.DirectWrite.TextLayout.SetDrawingEffect(SharpDX.ComObject,SharpDX.DirectWrite.TextRange)" /> method).  </param>
 /// <unmanaged>void ID2D1RenderTarget::DrawTextLayout([None] D2D1_POINT_2F origin,[In] IDWriteTextLayout* textLayout,[In] ID2D1Brush* defaultForegroundBrush,[None] D2D1_DRAW_TEXT_OPTIONS options)</unmanaged>
 public void DrawTextLayout(RawVector2 origin, TextLayout textLayout, Brush defaultForegroundBrush)
 {
     DrawTextLayout(origin, textLayout, defaultForegroundBrush, DrawTextOptions.None);
 }
예제 #47
0
        /// <summary>
        /// Updates the TextFormat and TextLayout.
        /// </summary>
        private void UpdateTextFormatAndLayout()
        {
            try
            {
                if (CurrentTextFormat != null)
                {
                    CurrentTextFormat.Dispose();
                    CurrentTextFormat = null;
                }

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

                FontText = "SharpDX - This font was loaded from a resource";

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

                CurrentTextLayout = new TextLayout(FactoryDWrite, FontText, CurrentTextFormat, renderControl.ClientSize.Width, renderControl.ClientSize.Height);
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
        public async Task<System.IO.MemoryStream> RenderLabelToStream(
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {

            // Get stream
            var pngStream = new MemoryStream();

            using (var renderTarget = RenderLabel(
                imageWidth,
                imageHeight,
                foregroundColor,
                origin,
                textLayout,
                dpi,
                format,
                alpha))
            {

                pngStream.Position = 0;

                // Create a WIC outputstream
                using (var wicStream = new WICStream(FactoryImaging, pngStream))
                {

                    var size = renderTarget.PixelSize;

                    // Initialize a Png encoder with this stream
                    using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream))
                    {

                        // Create a Frame encoder
                        using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder))
                        {
                            wicFrameEncoder.Initialize();

                            // Create image encoder
                            ImageEncoder wicImageEncoder;
                            ImagingFactory2 factory2 = new ImagingFactory2();
                            wicImageEncoder = new ImageEncoder(factory2, D2DDevice);


                            var imgParams = new ImageParameters();
                            imgParams.PixelFormat =
                                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                                    AlphaMode.Premultiplied);

                            imgParams.PixelHeight = (int)size.Height;
                            imgParams.PixelWidth = (int)size.Width;

                            wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams);

                            //// Commit changes
                            wicFrameEncoder.Commit();
                            wicBitmapEncoder.Commit();

                            byte[] buffer = new byte[pngStream.Length];
                            pngStream.Position = 0;
                            await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length);
                        }
                    }
                }
            }

            return pngStream;
        }
        public SharpDX.Direct2D1.Bitmap1 RenderLabel (
            float imageWidth,
            float imageHeight,
            Color4 foregroundColor,
            Vector2 origin,
            TextLayout textLayout,
            float dpi = DEFAULT_DPI,
            SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied)
        {
            var renderTarget = CreateRenderTarget(imageWidth, imageHeight, dpi, format, alpha);

            using (var drawingContext = CreateDrawingContext(renderTarget))
            {
                // Begin our drawing
                drawingContext.BeginDraw();

                // Clear to transparent
                drawingContext.Clear(TransparentColor);

                // Create our brush to actually draw with
                var solidBrush = new SolidColorBrush(drawingContext, foregroundColor);
                // Draw the text to the bitmap
                drawingContext.DrawTextLayout(origin, textLayout, solidBrush);

                // End our drawing
                drawingContext.EndDraw();
            }

            return renderTarget;
        }
예제 #50
0
        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();
        }
예제 #51
0
 public Size MeasureText(string text, Font font)
 {
     float maxWidth = float.MaxValue;
     float maxHeight = float.MaxValue;
     var layout = new DW.TextLayout (factories.DWFactory, text, GetTextFormat (font), maxWidth, maxHeight);
     return new Size (layout.Metrics.Width, layout.Metrics.Height);
 }
예제 #52
0
        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);
        }
예제 #53
0
        private static void GetKerningInfo(CCRawList<char> charset)
        {
            _abcValues.Clear();

            var fontFace = new FontFace(_currentFont);
            
            var value = new ABCFloat[1];

            var glyphRun = new GlyphRun();
            glyphRun.FontFace = fontFace;
            glyphRun.FontSize = _currentDIP;

            var BrushColor = SharpDX.Color.White;
            /*
            SharpDX.DirectWrite.Matrix mtrx = new SharpDX.DirectWrite.Matrix();
            mtrx.M11 = 1F;
            mtrx.M12 = 0;
            mtrx.M21 = 0;
            mtrx.M22 = 1F;
            mtrx.Dx = 0;
            mtrx.Dy = 0;
            */
            //GlyphMetrics[] metrics = fontFace.GetGdiCompatibleGlyphMetrics(23, 1, mtrx, false, glyphIndices, false);

            //FontMetrics metr = fontFace.GetGdiCompatibleMetrics(23, 1, new SharpDX.DirectWrite.Matrix());
            //_pRenderTarget.DrawGlyphRun(new SharpDX.DrawingPointF(left, top), glyphRun, new SharpDX.Direct2D1.SolidColorBrush(_pRenderTarget, BrushColor), MeasuringMode.GdiClassic);
            int[] codePoints = new int[1];
            var unitsPerEm = fontFace.Metrics.DesignUnitsPerEm;
            var familyName = _currentFont.ToString();

            
            for (int i = 0; i < charset.Count; i++)
            {
                var ch = charset[i];
                if (!_abcValues.ContainsKey(ch))
                {
                    var textLayout = new TextLayout(FactoryDWrite, ch.ToString(), textFormat, unitsPerEm, unitsPerEm);

                    var tlMetrics = textLayout.Metrics;
                    var tlmWidth = tlMetrics.Width;
                    var tllWidth = tlMetrics.LayoutWidth;

                    codePoints[0] = (int)ch;
                    short[] glyphIndices = fontFace.GetGlyphIndices(codePoints);
                    glyphRun.Indices = glyphIndices;

                    var metrics = fontFace.GetDesignGlyphMetrics(glyphIndices, false);
                    
                    //var width = metrics[0].AdvanceWidth + metrics[0].LeftSideBearing + metrics[0].RightSideBearing;
                    //var glyphWidth = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //var abcWidth = _currentDIP * (float)width / unitsPerEm;

                    //value[0].abcfA = _currentFontSizeEm * (float)metrics[0].LeftSideBearing / unitsPerEm;
                    //value[0].abcfB = _currentFontSizeEm * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //value[0].abcfC = _currentFontSizeEm * (float)metrics[0].RightSideBearing / unitsPerEm;

                    // The A and C values are throwing the spacing off
                    //value[0].abcfA = _currentDIP * (float)metrics[0].LeftSideBearing / unitsPerEm;
                    value[0].abcfB = _currentDIP * (float)metrics[0].AdvanceWidth / unitsPerEm;
                    //value[0].abcfC = _currentDIP * (float)metrics[0].RightSideBearing / unitsPerEm;

                    _abcValues.Add(
                        ch,
                        new KerningInfo()
                        {
                            A = value[0].abcfA,
                            B = value[0].abcfB,
                            C = value[0].abcfC
                        });
                }
            }

        }
예제 #54
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();
        }
        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;

            bool hasPremultipliedAlpha;

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

            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


            if (labelRenderer == null)
                labelRenderer = new CCLabel_Renderer81();

            try
            {

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

                using (var pngStream = labelRenderer.RenderLabelToStream(imageWidth, imageHeight, foregroundColor,
                    new Vector2(boundingRect.X, yOffset), textLayout).Result)
                {
                    // Create the Texture2D from the png stream
                    tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, pngStream);

                }

                // 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 (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();
        }
예제 #56
0
 /// <summary>	
 /// Draws the formatted text described by the specified <see cref="T:SharpDX.DirectWrite.TextLayout" /> object.	
 /// </summary>	
 /// <remarks>	
 /// When drawing the same text repeatedly, using the DrawTextLayout method is more efficient than using the {{DrawText}} method because the text doesn't need to be formatted and the layout processed with each call. This method doesn't return an error code if it fails. To determine whether a drawing operation (such as DrawTextLayout) failed, check the result returned by the <see cref="M:SharpDX.Direct2D1.RenderTarget.EndDraw(System.Int64@,System.Int64@)" /> or <see cref="M:SharpDX.Direct2D1.RenderTarget.Flush(System.Int64@,System.Int64@)" /> methods.  	
 /// </remarks>	
 /// <param name="origin">The point, described in device-independent pixels, at which the upper-left corner of the text described by textLayout is drawn. </param>
 /// <param name="textLayout">The formatted text to draw. Any drawing effects that do not inherit from <see cref="T:SharpDX.Direct2D1.Resource" /> are ignored. If there are drawing effects that inherit from ID2D1Resource that are not brushes, this method fails and the render target is put in an error state.  </param>
 /// <param name="defaultForegroundBrush">The brush used to paint any text in textLayout that does not already have a brush associated with it as a drawing effect (specified by the <see cref="M:SharpDX.DirectWrite.TextLayout.SetDrawingEffect(SharpDX.ComObject,SharpDX.DirectWrite.TextRange)" /> method).  </param>
 /// <unmanaged>void ID2D1RenderTarget::DrawTextLayout([None] D2D1_POINT_2F origin,[In] IDWriteTextLayout* textLayout,[In] ID2D1Brush* defaultForegroundBrush,[None] D2D1_DRAW_TEXT_OPTIONS options)</unmanaged>
 public void DrawTextLayout(DrawingPointF origin, TextLayout textLayout, Brush defaultForegroundBrush)
 {
     DrawTextLayout(origin, textLayout, defaultForegroundBrush, DrawTextOptions.None);
 }
예제 #57
0
        protected override DX11VertexGeometry GetGeom(DX11RenderContext device, int slice)
        {
            if (d2dFactory == null)
            {
                d2dFactory = new D2DFactory();
                dwFactory = new DWriteFactory(SharpDX.DirectWrite.FactoryType.Shared);
            }

            TextFormat fmt = new TextFormat(dwFactory, this.FFontInput[slice].Name, FFontSize[slice]);

            TextLayout tl = new TextLayout(dwFactory, FText[slice], fmt, 0.0f, 32.0f);
            tl.WordWrapping = WordWrapping.NoWrap;
            tl.TextAlignment = FHAlignment[slice];
            tl.ParagraphAlignment = FVAlignment[slice];

            OutlineRenderer renderer = new OutlineRenderer(d2dFactory);
            Extruder ex = new Extruder(d2dFactory);

            tl.Draw(renderer, 0.0f, 0.0f);

            var result = ex.GetVertices(renderer.GetGeometry(), this.FExtrude[slice]);

            Vector3 min = new Vector3(float.MaxValue);
            Vector3 max = new Vector3(float.MinValue);

            result.ForEach(pn =>
            {
                min.X = pn.Position.X < min.X ? pn.Position.X : min.X;
                min.Y = pn.Position.Y < min.Y ? pn.Position.Y : min.Y;
                min.Z = pn.Position.Z < min.Z ? pn.Position.Z : min.Z;

                max.X = pn.Position.X > max.X ? pn.Position.X : max.X;
                max.Y = pn.Position.Y > max.Y ? pn.Position.Y : max.Y;
                max.Z = pn.Position.Z > max.Z ? pn.Position.Z : max.Z;
            });

            SlimDX.DataStream ds = new SlimDX.DataStream(result.Count * Pos3Norm3VertexSDX.VertexSize, true, true);
            ds.Position = 0;

            ds.WriteRange(result.ToArray());

            ds.Position = 0;

            var vbuffer = new SlimDX.Direct3D11.Buffer(device.Device, ds, new SlimDX.Direct3D11.BufferDescription()
            {
                BindFlags = SlimDX.Direct3D11.BindFlags.VertexBuffer,
                CpuAccessFlags = SlimDX.Direct3D11.CpuAccessFlags.None,
                OptionFlags = SlimDX.Direct3D11.ResourceOptionFlags.None,
                SizeInBytes = (int)ds.Length,
                Usage = SlimDX.Direct3D11.ResourceUsage.Default
            });

            ds.Dispose();

            DX11VertexGeometry vg = new DX11VertexGeometry(device);
            vg.InputLayout = Pos3Norm3VertexSDX.Layout;
            vg.Topology = SlimDX.Direct3D11.PrimitiveTopology.TriangleList;
            vg.VertexBuffer = vbuffer;
            vg.VertexSize = Pos3Norm3VertexSDX.VertexSize;
            vg.VerticesCount = result.Count;
            vg.HasBoundingBox = true;
            vg.BoundingBox = new SlimDX.BoundingBox(new SlimDX.Vector3(min.X, min.Y, min.Z), new SlimDX.Vector3(max.X, max.Y, max.Z));

            return vg;
        }
예제 #58
0
        private void UpdateTextSettings()
        {
            if (UpdateSettings)
            {
                Destroy(ref Format);
                Destroy(ref Layout);

                Format = Tag(new TextFormat(Window.FactoryDW, Font, Weight, Style, Size));
                Layout = Tag(new TextLayout(Window.FactoryDW, Text, Format, Width, Height));
            }
        }
예제 #59
0
        /// <summary>
        /// Now that we have a CoreWindow object, the DirectX device/context can be created.
        /// </summary>
        /// <param name="entryPoint"></param>
        public async void Load(string entryPoint)
        {
            // Get the default hardware device and enable debugging. Don't care about the available feature level.
            // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop.
            SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

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

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

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

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

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

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

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

            // Create the DirectWrite factory objet.
            SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory();

            // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs.
            textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f);

            // Create two TextLayout objects for rendering the moving text.
            textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f);
            textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f);

            // Vertical offset for the moving text.
            layoutY = 0.0f;

            // Create the brushes for the text background and text color.
            backgroundBrush = new SolidColorBrush(d2dContext, Color.White);
            textBrush = new SolidColorBrush(d2dContext, Color.Black);
        }
예제 #60
0
 internal D2dTextLayout(string text, TextLayout textLayout)
     : base(textLayout)
 {
     m_nativeTextLayout = textLayout;
     m_text = text;
 }