Esempio n. 1
0
        private void ProcessTextFormat(CanvasDrawingSession drawingSession, CanvasTextFormat format)
        {
            CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, "Q", format, 0.0f, 0.0f);

            if (CharacterWidth != textLayout.DrawBounds.Width || CharacterHeight != textLayout.DrawBounds.Height)
            {
                CharacterWidth  = textLayout.DrawBounds.Right;
                CharacterHeight = textLayout.DrawBounds.Bottom;
            }

            int columns = Convert.ToInt32(Math.Floor(canvas.RenderSize.Width / CharacterWidth));
            int rows    = Convert.ToInt32(Math.Floor(canvas.RenderSize.Height / CharacterHeight));

            if (Columns != columns || Rows != rows)
            {
                Columns = columns;
                Rows    = rows;
                ResizeTerminal();

                if (_stream != null && _stream.CanWrite)
                {
                    _stream.SendWindowChangeRequest((uint)columns, (uint)rows, 800, 600);
                }
            }
        }
Esempio n. 2
0
        public Rect DrawText(char character, Paint paint)
        {
            var gradient = paint.Shader as Gradient;
            var brush    = gradient != null?gradient.GetBrush(_device, paint.Alpha) : new CanvasSolidColorBrush(_device, paint.Color);

            brush = paint.ColorFilter?.Apply(this, brush) ?? brush;

            UpdateDrawingSessionWithFlags(paint.Flags);
            _drawingSession.Transform = GetCurrentTransform();

            var text = new string(character, 1);

            var textFormat = new CanvasTextFormat
            {
                FontSize            = paint.TextSize,
                FontFamily          = paint.Typeface.FontFamily,
                FontStyle           = paint.Typeface.Style,
                FontWeight          = paint.Typeface.Weight,
                VerticalAlignment   = CanvasVerticalAlignment.Center,
                HorizontalAlignment = CanvasHorizontalAlignment.Left,
                LineSpacingBaseline = 0,
                LineSpacing         = 0
            };
            var textLayout = new CanvasTextLayout(_drawingSession, text, textFormat, 0.0f, 0.0f);

            _drawingSession.DrawText(text, 0, 0, brush, textFormat);

            if (gradient == null)
            {
                brush.Dispose();
            }

            return(textLayout.LayoutBounds);
        }
        public static CanvasGeometry CreateGeometry(
            float size,
            FontVariant selectedVariant,
            Character selectedChar,
            CanvasTextLayoutAnalysis analysis,
            CanvasTypography typography)
        {
            CanvasDevice device = Utils.CanvasDevice;

            /* SVG Exports render at fixed size - but a) they're vectors, and b) they're
             * inside an auto-scaling viewport. So render-size is *largely* pointless */
            float canvasH = size, canvasW = size, fontSize = size;

            using (CanvasTextLayout layout = new CanvasTextLayout(device, $"{selectedChar.Char}", new CanvasTextFormat
            {
                FontSize = fontSize,
                FontFamily = selectedVariant.Source,
                FontStretch = selectedVariant.FontFace.Stretch,
                FontWeight = selectedVariant.FontFace.Weight,
                FontStyle = selectedVariant.FontFace.Style,
                HorizontalAlignment = CanvasHorizontalAlignment.Center
            }, canvasW, canvasH))
            {
                layout.SetTypography(0, 1, typography);
                layout.Options = analysis.GlyphFormats.Contains(GlyphImageFormat.Svg) ? CanvasDrawTextOptions.EnableColorFont : CanvasDrawTextOptions.Default;

                return(CanvasGeometry.CreateText(layout));
            }
        }
        public void Draw(CanvasAnimatedDrawEventArgs args, Vector2 position, CanvasTextFormat font)
        {
            if (LastFont == null || LastFont.FontFamily != font.FontFamily || LastFont.FontSize != font.FontSize)
            {
                Widths.Clear();

                // recalculate widths
                for (int i = 0; i < Parts.Count; i++)
                {
                    CanvasTextLayout layoutTemp = new CanvasTextLayout(args.DrawingSession, Parts[i].String.Replace(' ', '.'), font, 0, 0);
                    Widths.Add((float)layoutTemp.LayoutBounds.Width);
                }

                LastFont = font;
            }

            float fOffsetX = 0.0f;

            for (int i = 0; i < Parts.Count; i++)
            {
                // draw string part
                args.DrawingSession.DrawText(Parts[i].String, new Vector2(position.X + fOffsetX, position.Y), Parts[i].Color, font);

                // add to offset
                fOffsetX += Widths[i];
            }
        }
Esempio n. 5
0
        void EnsureResources(ICanvasResourceCreatorWithDpi resourceCreator, Size targetSize)
        {
            if (!needsResourceRecreation)
            {
                return;
            }

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

            textLayout = CreateTextLayout(resourceCreator, (float)targetSize.Width, (float)targetSize.Height);

            if (CurrentTextOutlineGranularityOption == TextOutlineGranularity.Layout)
            {
                textGeometry = CanvasGeometry.CreateText(textLayout);
            }
            else
            {
                GlyphRunsToGeometryConverter converter = new GlyphRunsToGeometryConverter(resourceCreator);

                textLayout.DrawToTextRenderer(converter, 0, 0);

                textGeometry = converter.GetGeometry();
            }

            needsResourceRecreation = false;
        }
Esempio n. 6
0
            public void DrawGlyphRun(
                Vector2 position,
                CanvasFontFace fontFace,
                float fontSize,
                CanvasGlyph[] glyphs,
                bool isSideways,
                uint bidiLevel,
                object brush,
                CanvasTextMeasuringMode measuringMode,
                string locale,
                string textString,
                int[] custerMapIndices,
                uint textPosition,
                CanvasGlyphOrientation glyphOrientation)
            {
                if (glyphs == null)
                {
                    return;
                }

                var previousTransform = drawingSession.Transform;

                drawingSession.Transform = CanvasTextLayout.GetGlyphOrientationTransform(glyphOrientation, isSideways, position);

                drawingSession.DrawGlyphRun(
                    position,
                    fontFace,
                    fontSize,
                    glyphs,
                    isSideways,
                    bidiLevel,
                    textBrush);

                drawingSession.Transform = previousTransform;
            }
        public RichListBox(CanvasDevice device, Vector2 position, int width, int height, string title, CanvasTextFormat titleFont, CanvasTextFormat stringsFont, int maxStrings = 0)
        {
            // base(device, position, width, 0, title, titleFont)
            Position = position;

            // title
            Title         = new CanvasTextLayout(device, title, titleFont, 0, 0);
            TitlePosition = new Vector2(Position.X + Padding, Position.Y + Padding);

            // width is derived from title bounds
            Width  = width; //(int)Title.LayoutBounds.Width + Padding * 2;
            Height = height;

            // bar under title
            BarUnderTitleLeft  = new Vector2(Position.X, Position.Y + Padding * 2 + (float)Title.LayoutBounds.Height);
            BarUnderTitleRight = new Vector2(Position.X + Width, Position.Y + Padding * 2 + (float)Title.LayoutBounds.Height);

            // strings
            StringsFont       = stringsFont;
            StringsTextLayout = new CanvasTextLayout(device, "THIS IS A PRETTY GOOD TEMP STRING", StringsFont, 0, 0);
            StringsPosition   = new Vector2(Position.X + Padding, BarUnderTitleRight.Y + Padding);

            MaxStrings = maxStrings == 0 ? 1000 : maxStrings;

            BorderRectangle = new Rect(Position.X, Position.Y, Width, Height);
        }
Esempio n. 8
0
        public void Measure(Win2DRenderable renderable, ICanvasResourceCreator resourceCreator)
        {
            var text = renderable.Node.Text;

            if (isFirstMeasure || !string.Equals(text, lastText, StringComparison.CurrentCulture))
            {
                isFirstMeasure = true;

                lastText = text;

                if (!string.IsNullOrWhiteSpace(text))
                {
                    using (var textLayout = new CanvasTextLayout(resourceCreator, text, TextFormat, 0.0f, 0.0f))
                    {
                        renderSize = new Vector2(
                            (float)textLayout.DrawBounds.Width,
                            (float)textLayout.DrawBounds.Height);
                    }
                }
                else
                {
                    renderSize = Vector2.Zero;
                }

                renderSize.Y = Math.Max(renderSize.Y, TextFormat.FontSize * 1.5f) + PaddingY;
                renderSize.X = Math.Max(renderSize.X, TextFormat.FontSize * 2);

                renderSize = MathHelper.RoundToMultipleOfTwo(renderSize);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Create a specific geometry.
        /// </summary>
        /// <param name="resourceCreator"> The resource-creator. </param>
        /// <returns> The product geometry. </returns>
        public override CanvasGeometry CreateGeometry(ICanvasResourceCreator resourceCreator)
        {
            Transformer transformer = base.Transform.Transformer;


            CanvasTextFormat textFormat = new CanvasTextFormat
            {
                FontSize   = this.FontSize,
                FontFamily = this.FontFamily,

                HorizontalAlignment = this.FontAlignment,
                FontStyle           = this.FontStyle,
                FontWeight          = this.FontWeight,
            };

            float           width  = transformer.Horizontal.Length();
            float           height = transformer.Vertical.Length();
            TransformerRect rect   = new TransformerRect(width, height, Vector2.Zero);
            Matrix3x2       matrix = Transformer.FindHomography(rect, transformer);

            CanvasTextLayout textLayout = new CanvasTextLayout(resourceCreator, this.FontText, textFormat, width, height);
            CanvasGeometry   geometry   = CanvasGeometry.CreateText(textLayout).Transform(matrix);


            return(geometry);
        }
 private void CreateTextLayoutBeforeCursor(ICanvasResourceCreator resourceCreator)
 {
     if (Text != null)
     {
         TextBeforeCursor = new CanvasTextLayout(resourceCreator, Text.Substring(0, CursorStringIndex), Statics.DefaultFontNoWrap, 0, 0);
     }
 }
        private void AnimatedControl_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
        {
            // Initialize the brushes.
            backgroundDefaultBrush = CreateRadialGradientBrush(sender,
                                                               Color.FromArgb(0x00, 0x6E, 0xEF, 0xF8), Color.FromArgb(0x4D, 0x6E, 0xEF, 0xF8));
            backgroundAnswerCorrectBrush = CreateRadialGradientBrush(sender,
                                                                     Color.FromArgb(0x00, 0x42, 0xC9, 0xC5), Color.FromArgb(0x4D, 0x42, 0xC9, 0xC5));
            backgroundAnswerIncorrectBrush = CreateRadialGradientBrush(sender,
                                                                       Color.FromArgb(0x00, 0xDE, 0x01, 0x99), Color.FromArgb(0x4D, 0xDE, 0x01, 0x99));
            borderDefaultBrush  = new CanvasSolidColorBrush(sender, Color.FromArgb(0xFF, 0x6E, 0xEF, 0xF8));
            borderGradientBrush = new CanvasLinearGradientBrush(sender,
                                                                Color.FromArgb(0xFF, 0x0F, 0x56, 0xA4), Color.FromArgb(0xFF, 0x6E, 0xEF, 0xF8))
            {
                StartPoint = new Vector2(centerPoint.X - radius, centerPoint.Y),
                EndPoint   = new Vector2(centerPoint.X + radius, centerPoint.Y)
            };
            borderAnswerCorrectBrush   = new CanvasSolidColorBrush(sender, Color.FromArgb(0xFF, 0x42, 0xC9, 0xC5));
            borderAnswerIncorrectBrush = new CanvasSolidColorBrush(sender, Color.FromArgb(0xFF, 0xDE, 0x01, 0x99));

            // Calculate the text position for vertical centering to account for the
            // fact that text is not vertically centered within its layout bounds.
            var textLayout        = new CanvasTextLayout(sender, "0123456789", textFormat, 0, 0);
            var drawMidpoint      = (float)(textLayout.DrawBounds.Top + (textLayout.DrawBounds.Height / 2));
            var layoutMidpoint    = (float)(textLayout.LayoutBounds.Top + (textLayout.LayoutBounds.Height / 2));
            var textPositionDelta = drawMidpoint - layoutMidpoint;

            textPosition = new Vector2(centerPoint.X, centerPoint.Y - textPositionDelta);
        }
        private async Task savePreviewAsync(int maxWidth = 256, int maxHeight = 256)
        {
            if (This.Content != null)
            {
                // a4 pixel size 96 dpi = 794 x 1123
                CanvasDevice       device       = CanvasDevice.GetSharedDevice(true);
                CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, 794, 1123, 96);

                var mergedStream = new InMemoryRandomAccessStream();
                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(Colors.White);
                    var textContent = Encoding.UTF8.GetString(This.Content);
                    //CanvasSolidColorBrush textBrush = new CanvasSolidColorBrush(device, Colors.Red);
                    CanvasTextFormat textFormat = new CanvasTextFormat();
                    CanvasTextLayout textLayout = new CanvasTextLayout(device, textContent, textFormat, 600, 900);

                    ds.DrawTextLayout(textLayout, new Vector2(100, 100), Colors.Black);
                }
                await renderTarget.SaveAsync(mergedStream, CanvasBitmapFileFormat.Jpeg);

                //StorageFile between = await DownloadsFolder.CreateFileAsync("between.jpg", CreationCollisionOption.GenerateUniqueName);
                //using (var fileStream = await between.OpenAsync(FileAccessMode.ReadWrite))
                //{
                //  await RandomAccessStream.CopyAsync(mergedStream, fileStream);
                //}

                // scaling result
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(mergedStream);

                using (var previewStream = new InMemoryRandomAccessStream())
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(previewStream, decoder);

                    var ratioWidth  = (double)maxWidth / decoder.PixelWidth;
                    var ratioHeight = (double)maxHeight / decoder.PixelHeight;
                    var ratioScale  = Math.Min(ratioWidth, ratioHeight);

                    var aspectHeight = (uint)(ratioScale * decoder.PixelHeight);
                    var aspectWidth  = (uint)(ratioScale * decoder.PixelWidth);

                    //encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
                    encoder.BitmapTransform.ScaledHeight = aspectHeight;
                    encoder.BitmapTransform.ScaledWidth  = aspectWidth;
                    await encoder.FlushAsync();

                    // write result to preview
                    using (var reader = new DataReader(previewStream.GetInputStreamAt(0)))
                    {
                        This.Preview = new byte[previewStream.Size];
                        await reader.LoadAsync((uint)previewStream.Size);

                        reader.ReadBytes(This.Preview);
                    }

                    //StorageFile previewFile = await DownloadsFolder.CreateFileAsync("preview.jpg", CreationCollisionOption.GenerateUniqueName);
                    //await FileIO.WriteBytesAsync(previewFile, This.Preview);
                }
            }
        }
Esempio n. 13
0
        private void canvas_RegionsInvalidated(CanvasVirtualControl sender, CanvasRegionsInvalidatedEventArgs args)
        {
            foreach (var region in args.InvalidatedRegions)
            {
                using (var ds = sender.CreateDrawingSession(region))
                {
                    ds.Clear(Colors.Transparent);

                    int startLine = (int)Math.Floor(region.Top / LineHeight);

                    // add 2 to the end line count. we want to "overdraw" a bit if the line is going to be cut-off
                    int endLine = (int)(Math.Ceiling(region.Bottom / LineHeight) + 2);

                    var stringRegion = new StringBuilder();
                    for (int i = startLine; i < endLine; i++)
                    {
                        if (Text != null && i < Text.LineCount)
                        {
                            var textLine = Text.GetLine(i);
                            if (textLine != null && textLine is DiffTextLine diffLine)
                            {
                                stringRegion.AppendLine(diffLine.LineNo > -1 ? (diffLine.LineNo).ToString() : "");
                            }
                        }
                    }

                    using (var canvasText = new CanvasTextLayout(ds, stringRegion.ToString(), _textFormat, 32, (float)region.Height))
                    {
                        ds.DrawTextLayout(canvasText, 0, startLine * LineHeight, _defaultForegroundBrush);
                    }
                }
            }
        }
Esempio n. 14
0
        public Image <Rgba32> SearchAndReplace(Image <Rgba32> masterImage, int ratio = 5)
        {
            Text = GenerateText(masterImage, ratio);

            CanvasDevice     device     = CanvasDevice.GetSharedDevice();
            CanvasTextFormat textFormat = new CanvasTextFormat()
            {
                FontFamily          = "Courier New",
                FontSize            = 14,
                HorizontalAlignment = CanvasHorizontalAlignment.Left,
                VerticalAlignment   = CanvasVerticalAlignment.Top,
                WordWrapping        = CanvasWordWrapping.NoWrap
            };
            var textLayout = new CanvasTextLayout(device, Text, textFormat, 100, 100);

            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (float)textLayout.LayoutBounds.Width,
                                                                     (float)textLayout.LayoutBounds.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
                ds.DrawTextLayout(textLayout, 0, 0, Colors.Black);
            }

            return(Generate(renderTarget).Result);
        }
 public BackgroundAnimatedCharacter(CanvasDevice device, char c, Color color)
 {
     _color     = color;
     Character  = c;
     TextLayout = new CanvasTextLayout(device, c.ToString(), HarryP, 0, 0);
     _boundary  = new Rect(0, 0, 100, 150);
 }
Esempio n. 16
0
        private void AnnotateView(CanvasDrawingSession drawingSession)
        {
            CanvasTextFormat lineNumberFormat =
                new CanvasTextFormat
            {
                FontSize     = Convert.ToSingle(canvas.FontSize / 2),
                FontFamily   = canvas.FontFamily.Source,
                FontWeight   = canvas.FontWeight,
                WordWrapping = CanvasWordWrapping.NoWrap
            };

            for (var i = 0; i < Rows; i++)
            {
                string s          = i.ToString();
                var    textLayout = new CanvasTextLayout(drawingSession, s.ToString(), lineNumberFormat, 0.0f, 0.0f);
                float  y          = i * (float)CharacterHeight;
                drawingSession.DrawLine(0, y, (float)canvas.RenderSize.Width, y, Colors.Beige);
                drawingSession.DrawTextLayout(textLayout, (float)(canvas.RenderSize.Width - (CharacterWidth / 2 * s.Length)), y, Colors.Yellow);

                s          = (i + 1).ToString();
                textLayout = new CanvasTextLayout(drawingSession, s.ToString(), lineNumberFormat, 0.0f, 0.0f);
                drawingSession.DrawTextLayout(textLayout, (float)(canvas.RenderSize.Width - (CharacterWidth / 2 * (s.Length + 3))), y, Colors.Green);
            }

            var bigText       = Terminal.DebugText;
            var bigTextLayout = new CanvasTextLayout(drawingSession, bigText, lineNumberFormat, 0.0f, 0.0f);

            drawingSession.DrawTextLayout(bigTextLayout, (float)(canvas.RenderSize.Width - bigTextLayout.DrawBounds.Width - 100), 0, Colors.Yellow);
        }
Esempio n. 17
0
        private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            var textFormat = new CanvasTextFormat()
            {
                FontSize    = (float)FontSize,
                FontFamily  = FontFamily.Source,
                FontStretch = FontStretch,
                FontWeight  = FontWeight,
                FontStyle   = FontStyle
            };

            switch (TextWrapping)
            {
            case TextWrapping.NoWrap:
                textFormat.WordWrapping = CanvasWordWrapping.NoWrap;
                break;

            case TextWrapping.Wrap:
                textFormat.WordWrapping = CanvasWordWrapping.Wrap;
                break;

            case TextWrapping.WrapWholeWords:
                textFormat.WordWrapping = CanvasWordWrapping.WholeWord;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(TextWrapping));
            }

            _textLayout = new CanvasTextLayout(sender, Text, textFormat, (float)sender.Size.Width, (float)sender.Size.Height);

            args.DrawingSession.DrawGeometry(CanvasGeometry.CreateText(_textLayout), Foreground.ToCanvasBrush(sender), (float)StrokeThickness);
        }
Esempio n. 18
0
        private void ProcessTextFormat(CanvasDrawingSession drawingSession, CanvasTextFormat format)
        {
            CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, "\u2560", format, 0.0f, 0.0f);

            if (CharacterWidth != textLayout.DrawBounds.Width || CharacterHeight != textLayout.DrawBounds.Height)
            {
                CharacterWidth  = textLayout.DrawBounds.Right;
                CharacterHeight = textLayout.DrawBounds.Bottom;
            }

            int columns = Convert.ToInt32(Math.Floor(canvas.RenderSize.Width / CharacterWidth));
            int rows    = Convert.ToInt32(Math.Floor(canvas.RenderSize.Height / CharacterHeight));

            if (Columns != columns || Rows != rows)
            {
                Columns = columns;
                Rows    = rows;
                ResizeTerminal();



                //if (VtConnection != null)
                //    VtConnection.SetTerminalWindowSize(columns, rows, 800, 600);
            }
        }
Esempio n. 19
0
        private CanvasTextLayout CreateTextLayout(ICanvasResourceCreator resourceCreator, float canvasWidth, float canvasHeight)
        {
            float sizeDim = Math.Min(canvasWidth, canvasHeight);

            CanvasTextFormat textFormat = new CanvasTextFormat()
            {
                FontSize  = ThumbnailGenerator.IsDrawingThumbnail ? sizeDim * 0.25f : sizeDim * 0.085f,
                Direction = CurrentTextDirection,
            };

            CanvasTextLayout textLayout = new CanvasTextLayout(resourceCreator, testString, textFormat, canvasWidth, canvasHeight);

            if (CurrentTextEffectOption == TextEffectOption.UnderlineEveryOtherWord)
            {
                foreach (Utils.WordBoundary wb in everyOtherWordBoundary)
                {
                    textLayout.SetUnderline(wb.Start, wb.Length, true);
                }
            }
            else if (CurrentTextEffectOption == TextEffectOption.StrikeEveryOtherWord)
            {
                foreach (Utils.WordBoundary wb in everyOtherWordBoundary)
                {
                    textLayout.SetStrikethrough(wb.Start, wb.Length, true);
                }
            }

            textLayout.VerticalGlyphOrientation = CurrentVerticalGlyphOrientation;

            return(textLayout);
        }
Esempio n. 20
0
        public void FormatLine(ILanguage language,
                               CanvasVirtualControl canvas, CanvasTextLayout canvasText, string content)
        {
            var offset = 0;

            base.languageParser.Parse(content, language,
                                      (parsedCode, captures) =>
            {
                foreach (var capture in captures)
                {
                    if (base.Styles.Contains(capture.Name))
                    {
                        var style = base.Styles[capture.Name];

                        if (!string.IsNullOrEmpty(style.Foreground))
                        {
                            var foregroundBrush = GetSolidColorBrush(canvas, style.Foreground);
                            canvasText.SetBrush(
                                capture.Index + offset,
                                capture.Length, foregroundBrush);
                        }
                    }
                }

                offset += parsedCode.Length;
            });
        }
Esempio n. 21
0
        void DrawText(CanvasTextLayout textLayout)
        {
            #region unused
            // text drawer method 1 - no anti-aliasing feature
            //var layout = new CanvasTextLayout(_device, Text, textformat, (float)Width, (float)Height);
            //var geometry = CanvasGeometry.CreateText(layout);
            //var compPath = new CompositionPath(geometry);
            //var pathGeo = _compositor.CreatePathGeometry(compPath);

            // set to container
            //var w = _compositor.CreateSpriteShape(pathGeo);
            //w.FillBrush = _compositor.CreateColorBrush(Color.FromArgb(0xd7, 0xff, 0xff, 0xff));
            //_shape.Shapes.Add(w);
            #endregion

            // text drawer - with anti-aliasing feature
            using var ds = CanvasComposition.CreateDrawingSession(_drawsurface);

            ds.Antialiasing = CanvasAntialiasing.Antialiased;
            //ds.DrawText(Text, rectext, Color.FromArgb(0xd7, 0xff, 0xff, 0xff), textformat);
            ds.DrawTextLayout(textLayout, (float)Width / 2, (float)Height / 2, Color.FromArgb(0xd7, 0xff, 0xff, 0xff));
            ds.Flush();
            ds.Dispose();

            // set to container
            var brush  = _compositor.CreateSurfaceBrush(_drawsurface);
            var sprite = _compositor.CreateSpriteVisual();
            sprite.Brush = brush;
            sprite.Size  = _size;
            _shape.Children.InsertAtTop(sprite);
        }
Esempio n. 22
0
        /// <summary>
        /// Draw the stuff on the canvas
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void CanvasControl_Draw(
            Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender,
            Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs args)
        {
            Debug.WriteLine("canvas draw");
            CanvasDrawingSession ds = args.DrawingSession;

            if (this.currentGraph != null)
            {
                this.currentGraph.Draw(args.DrawingSession);
            }
            else
            {
                Single           x      = (Single)(this.MainCanvas.ActualWidth / 2);
                Single           y      = (Single)(this.MainCanvas.ActualHeight / 2);
                CanvasTextFormat format = new CanvasTextFormat
                {
                    FontSize     = 30.0f,
                    WordWrapping = CanvasWordWrapping.NoWrap
                };

                CanvasTextLayout textLayout = new CanvasTextLayout(ds,
                                                                   "Nothing to see here.", format, 0.0f, 0.0f);
                Rect   bounds = textLayout.LayoutBounds;
                Single newX   = (Single)((this.MainCanvas.ActualWidth / 2) - (bounds.Width / 2));
                Single newY   = (Single)((this.MainCanvas.ActualHeight / 2) - (bounds.Height / 2));

                ds.DrawTextLayout(textLayout, newX, newY, Colors.White);
            }
        }
        public bool DrawString(
            CanvasDrawingSession graphics,
            CanvasTextLayout textLayout,
            float x, float y)
        {
            using (CanvasGeometry geometry = CanvasGeometry.CreateText(textLayout))
            {
                CanvasStrokeStyle stroke = new CanvasStrokeStyle();
                stroke.DashStyle = CanvasDashStyle.Solid;
                stroke.DashCap   = CanvasCapStyle.Round;
                stroke.StartCap  = CanvasCapStyle.Round;
                stroke.EndCap    = CanvasCapStyle.Round;
                stroke.LineJoin  = CanvasLineJoin.Round;

                for (int i = 1; i <= m_nThickness; ++i)
                {
                    graphics.DrawGeometry(geometry, x, y, m_clrOutline, i, stroke);
                }

                if (m_bClrText)
                {
                    graphics.FillGeometry(geometry, x, y, m_clrText);
                }
                else
                {
                    graphics.FillGeometry(geometry, x, y, m_brushText);
                }
            }
            return(true);
        }
Esempio n. 24
0
        public void DrawString(string c)
        {
            sofar += c;
            using (
                var drawingSession = CanvasComposition.CreateDrawingSession(drawingSurface,
                                                                            new Rect(0, 0, ActualWidth, ActualHeight)))
            {
                CanvasTextFormat tf = new CanvasTextFormat()
                {
                    FontSize = 72
                };

                float            xLoc   = 100.0f;
                float            yLoc   = 100.0f;
                CanvasTextFormat format = new CanvasTextFormat
                {
                    FontSize     = 30.0f,
                    WordWrapping = CanvasWordWrapping.NoWrap
                };
                CanvasTextLayout textLayout = new CanvasTextLayout(drawingSession, sofar, format, 0.0f,
                                                                   0.0f);
                Rect theRectYouAreLookingFor = new Rect(xLoc + textLayout.DrawBounds.X,
                                                        yLoc + textLayout.DrawBounds.Y, textLayout.DrawBounds.Width, textLayout.DrawBounds.Height);
                drawingSession.DrawRectangle(theRectYouAreLookingFor, Colors.Green, 1.0f);
                drawingSession.DrawTextLayout(textLayout, xLoc, yLoc, Colors.Yellow);

                drawingSession.DrawInk(list);
            }
        }
Esempio n. 25
0
        void EnsureResources(ICanvasResourceCreatorWithDpi resourceCreator, Size targetSize)
        {
            if (resourceRealizationSize != targetSize && !needsResourceRecreation)
            {
                return;
            }

            float canvasWidth  = (float)targetSize.Width;
            float canvasHeight = (float)targetSize.Height;

            if (textLayout != null)
            {
                textLayout.Dispose();
            }
            textLayout = CreateTextLayout(resourceCreator, canvasWidth, canvasHeight);

            Rect layoutBounds = textLayout.LayoutBounds;

            textBrush            = new CanvasLinearGradientBrush(resourceCreator, Colors.Red, Colors.Green);
            textBrush.StartPoint = new System.Numerics.Vector2((float)(layoutBounds.Left + layoutBounds.Right) / 2, (float)layoutBounds.Top);
            textBrush.EndPoint   = new System.Numerics.Vector2((float)(layoutBounds.Left + layoutBounds.Right) / 2, (float)layoutBounds.Bottom);

            selectionTextBrush            = new CanvasLinearGradientBrush(resourceCreator, Colors.Green, Colors.Red);
            selectionTextBrush.StartPoint = textBrush.StartPoint;
            selectionTextBrush.EndPoint   = textBrush.EndPoint;

            needsResourceRecreation = false;
            resourceRealizationSize = targetSize;
        }
        virtual protected void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (null == this.Text)
            {
                return;
            }
            if (0 == this.TextFontSize)
            {
                return;
            }

            this.EnsureResources(sender, args);

            var ds = args.DrawingSession;

            using (var textFormat = new CanvasTextFormat()
            {
                HorizontalAlignment = this.TextHorizontalAlignment,
                VerticalAlignment = this.TextVerticalAlignment,
                FontSize = (float)this.TextFontSize,
                Options = CanvasDrawTextOptions.Default,
            })
            {
                var textLayout   = new CanvasTextLayout(sender, this.Text, textFormat, (float)this.GaugeWidth, (float)this.GaugeWidth);
                var layoutBounds = textLayout.LayoutBounds;

                double radians = this.TextAngle * Math.PI / 180D;
                ds.Transform *= Matrix3x2.CreateRotation((float)radians, new Vector2((float)layoutBounds.Width / 2F, (float)layoutBounds.Height / 2F));

                double x = Math.Cos(radians) * layoutBounds.Width / 2F;
                double y = -Math.Sin(radians) * layoutBounds.Height / 2F;
                ds.DrawTextLayout(textLayout, (float)x, (float)y, this.TextFontColor);
            }
        }
Esempio n. 27
0
        public UGTextLayout(IUGContext context, string textString, IUGTextFormat textFormat, UGSize requestedSize)
        {
            var device = ((UGContext)context).Device;
            var format = ((UGTextFormat)textFormat).Native;

            _native = new CanvasTextLayout(device, textString, format, requestedSize.Width, requestedSize.Height);
        }
Esempio n. 28
0
        private void DrawPage(CanvasDrawingSession drawingSession, Rect imageableRect, GraphSize graphSize, LabelLocation labelLocation)
        {
            drawingSession.Transform = GetPrintTransfrom(imageableRect, graphSize, out Size size);

            _graph.DrawGraph(drawingSession, size, Colors.Black);

            IReadOnlyList <IFunction> functions = _graph.Functions;

            if (functions == null || labelLocation == LabelLocation.None)
            {
                return;
            }

            // Draw function labels.
            string functionString = GetFunctionString(functions, out FuntionLocation[] locations);

            using (var layout = new CanvasTextLayout(drawingSession, functionString, LabelFormat, 100, 20))
            {
                foreach (FuntionLocation location in locations)
                {
                    int start = location.Start;
                    layout.SetColor(start, location.Length, location.Color);
                    int parenLocation = functionString.IndexOf('(', start);

                    // ++ for the f
                    layout.SetTypography(++start, parenLocation - start, SubScriptTypography);
                }

                Vector2 labelPoint = GetLabelLocation(labelLocation, layout.LayoutBounds, size);
                drawingSession.DrawTextLayout(layout, labelPoint, Colors.Black);
            }
        }
        private CanvasTextLayout CreateTextLayout(ICanvasResourceCreator resourceCreator, float canvasWidth, float canvasHeight)
        {
            float sizeDim = Math.Min(canvasWidth, canvasHeight);

            float fontSize;

            if (!ThumbnailGenerator.IsDrawingThumbnail)
            {
                testString = "Win2D supports the use of typography options with text. Typography affects how glyphs are positioned, how they appear, and may at times substitute glyphs with other glyphs. Typography features can be queried for font compatibility, or applied to any part of a text layout.";
                fontSize   = sizeDim * 0.075f;
            }
            else
            {
                testString = "Typography";
                fontSize   = sizeDim * 0.1f;
            }

            CanvasTextFormat textFormat = new CanvasTextFormat()
            {
                FontSize            = fontSize,
                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                VerticalAlignment   = CanvasVerticalAlignment.Center
            };

            textFormat.FontFamily = fontPicker.CurrentFontFamily;

            return(textLayout = new CanvasTextLayout(resourceCreator, testString, textFormat, canvasWidth, canvasHeight));
        }
        private void DrawRegion(CanvasVirtualImageSource sender, Rect region)
        {
            var tryPanningOrZoomingLayout = new CanvasTextLayout(sender.Device, "Try panning or zooming.", format, 500, 0);

            var infoLayout = new CanvasTextLayout(sender.Device,
                                                  "In this demo, each time a region is updated, it is cleared to a different background color.  " +
                                                  "This is to make it possible to see which regions get redrawn.",
                                                  format, 500, 0);

            var youMadeIt = new CanvasTextLayout(sender.Device,
                                                 "You made it to the end!", endFormat, 1000, 0);

            using (var ds = sender.CreateDrawingSession(NextColor(), region))
            {
                var left   = ((int)(region.X / gridSize) - 1) * gridSize;
                var top    = ((int)(region.Y / gridSize) - 1) * gridSize;
                var right  = ((int)((region.X + region.Width) / gridSize) + 1) * gridSize;
                var bottom = ((int)((region.Y + region.Height) / gridSize) + 1) * gridSize;

                for (var x = left; x <= right; x += gridSize)
                {
                    for (var y = top; y <= bottom; y += gridSize)
                    {
                        var pos = new Vector2((float)x, (float)y);
                        ds.DrawCircle(pos, 10, Colors.White);

                        ds.DrawText(string.Format("{0}\n{1}", x, y), pos, Colors.DarkBlue, coordFormat);
                    }
                }

                DrawTextWithBackground(ds, tryPanningOrZoomingLayout, gridSize / 2, gridSize / 2);
                DrawTextWithBackground(ds, infoLayout, gridSize * 3.5, gridSize * 5.5);
                DrawTextWithBackground(ds, youMadeIt, width - youMadeIt.RequestedSize.Width, height - youMadeIt.RequestedSize.Height);
            }
        }