public TextInfo(ICanvasResourceCreator rc, String text)
 {
     
     format = RendererSettings.getInstance().getLabelFont();
     textLayout = new CanvasTextLayout(rc, text, format, 0.0f, 0.0f);
     bounds = getTextBounds();
 }
        private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
        {
            var fontFormat = new Microsoft.Graphics.Canvas.Text.CanvasTextFormat
            {
                FontSize = 28,
            };

            args.DrawingSession.DrawRectangle(gameBoardConfig.GameBoard, Colors.Red);
            drawGameBoard(args, gameBoardConfig);

            scoreTextBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                             () => { scoreTextBox.Text = $"Score: {score}"; });
            bombsTextBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                             () => { bombsTextBox.Text = $"Bombs: {bombCount} bombs"; });
            flagsTextBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                             () => { flagsTextBox.Text = $"Flags: {flagCount} flags"; });
            timeTextBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                            () => { timeTextBox.Text = $"Time: {num} seconds"; });



            if (lastPoint.HasValue)
            {
                Point point = lastPoint.Value;

                double x = point.X;
                double y = point.Y;
                System.Numerics.Vector2 vec = new System.Numerics.Vector2(Convert.ToSingle(x), Convert.ToSingle(y));
                args.DrawingSession.DrawEllipse(vec, 10, 10, Colors.Red);
            }
        }
Exemplo n.º 3
0
        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];
            }
        }
        /// <summary>
        /// Создать карту.
        /// </summary>
        /// <param name="program">Программа.</param>
        /// <param name="width">Ширина.</param>
        /// <param name="fontSize">Размер шрифта.</param>
        /// <param name="maxLines">Максимальное число линий.</param>
        /// <returns>Карта.</returns>
        public ITextRender2MeasureMap CreateMap(ITextRender2RenderProgram program, double width, double fontSize, int? maxLines)
        {
            if (program == null) throw new ArgumentNullException(nameof(program));
            var interProgram = CreateIntermediateProgram(program).ToArray();
            var allText = interProgram.Aggregate(new StringBuilder(), (sb, s) => sb.Append(s.RenderString)).ToString();
            using (var tf = new CanvasTextFormat())
            {
                tf.FontFamily = "Segoe UI";
                tf.FontSize = (float)fontSize;
                tf.WordWrapping = CanvasWordWrapping.Wrap;
                tf.Direction = CanvasTextDirection.LeftToRightThenTopToBottom;
                tf.Options = CanvasDrawTextOptions.Default;

                var screen = DisplayInformation.GetForCurrentView();
                using (var ds = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float) width, 10f, screen.LogicalDpi))
                {
                    using (var tl = new CanvasTextLayout(ds, allText, tf, (float)width, 10f))
                    {
                        var helperArgs = interProgram.OfType<MappingHelperArg>().ToList();
                        mappingHelper.ApplyAttributes(tl, helperArgs, fontSize);
                        var map = AnalyzeMap(tl, allText).ToArray();
                        var result = new MeasureMap(map, width, maxLines, StrikethrougKoef);
                        return result;
                    }
                }
            }
        }
Exemplo n.º 5
0
        public InkExample()
        {
            this.InitializeComponent();

            inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch;

            // By default, pen barrel button or right mouse button is processed for inking
            // Set the configuration to instead allow processing these input on the UI thread
            inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;

            inkCanvas.InkPresenter.UnprocessedInput.PointerPressed += UnprocessedInput_PointerPressed;
            inkCanvas.InkPresenter.UnprocessedInput.PointerMoved += UnprocessedInput_PointerMoved;
            inkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInput_PointerReleased;

            inkCanvas.InkPresenter.StrokeInput.StrokeStarted += StrokeInput_StrokeStarted;

            inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
            inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;

            inkSynchronizer = inkCanvas.InkPresenter.ActivateCustomDrying();

            textFormat = new CanvasTextFormat();

            // Set defaults
            SelectedDryInkRenderingType = DryInkRenderingType.BuiltIn;
            SelectColor(color0);
            showTextLabels = true;

            needToCreateSizeDependentResources = true;
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
 public Txt(string content, Color col, CanvasTextFormat format)
 {
     Content = content;
     Color = col;
     Format = format;
     MetroSlideshow.WindowSizeUpdated += MetroSlideshow_WindowSizeUpdated;
 }
Exemplo n.º 8
0
 public NativeFont(int face, int style, int size, CanvasTextFormat font, String fileName, int height, int weight)
     : this(face, style, size, font)
 {
     this.fileName = fileName;
     this.height = height;
     this.weight = weight;
 }
Exemplo n.º 9
0
 public NativeFont(int face, int style, int size, CanvasTextFormat font)
 {
     this.face = face;
     this.style = style;
     this.size = size;
     this.font = font;
     this.font.FontSize = this.font.FontSize;
 }
Exemplo n.º 10
0
        public void Run(IBackgroundTaskInstance taskInstance)
        { 
            // 
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            _deferral = taskInstance.GetDeferral();

            Init().Wait();

            CanvasTextFormat txtFmt1 = new CanvasTextFormat
            {
                FontSize = 28,
                FontFamily = "Old English Five",
                LineSpacingMode = CanvasLineSpacingMode.Proportional,
                LineSpacingBaseline = 0.8f
            };

            CanvasTextFormat txtFmt2 = new CanvasTextFormat
            {
                FontSize = 18,
                FontFamily = "Segoe UI Emoji",
                LineSpacingMode = CanvasLineSpacingMode.Proportional,
                LineSpacingBaseline = 0.8f
            };

            //display on spi
            if (_displaySpi.State == SSD1603.States.Ready) {
                //draw
                using (CanvasDrawingSession ds = _displaySpi.Render.CreateDrawingSession())
                {
                    ds.Clear(SSD1603.BackgroundColor);
                    ds.DrawText("Hello", 0, 0, SSD1603.ForeColor, txtFmt1);
                }

                _displaySpi.Display();
            }

            //display on i2c
            if (_displayI2c.State == SSD1603.States.Ready)
            {
                //draw
                using (CanvasDrawingSession ds = _displayI2c.Render.CreateDrawingSession())
                {
                    ds.Antialiasing = CanvasAntialiasing.Aliased;
                    ds.TextAntialiasing = CanvasTextAntialiasing.Aliased;
                    //REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" /v "Astronaut III" /t REG_SZ /d "astronautiii.ttf"
                    ds.Clear(SSD1603.BackgroundColor);
                    ds.DrawText("\U0001F600\U00002603\U0001F341\U0001F50D", 0, 0, SSD1603.ForeColor, txtFmt2);
                }

                _displayI2c.Display();
            }
        }
        private void Draw(int updateLeft, int updateTop, int updateWidth, int updateHeight, Color color)
        {
            if (imageSource == null)
                return;

            int drawTextCalls = 0;

            try
            {
                using (var ds = imageSource.CreateDrawingSession(color, new Rect(updateLeft, updateTop, updateWidth, updateHeight)))
                {
                    CanvasTextFormat format = new CanvasTextFormat
                    {
                        FontSize = 16,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        VerticalAlignment = CanvasVerticalAlignment.Center
                    };

                    // Round update region to step
                    updateLeft = (updateLeft / step) * step;
                    updateTop = (updateTop / step) * step;
                    int updateRight = updateLeft + ((updateWidth / step) + 1) * step;
                    int updateBottom = updateTop + ((updateHeight / step) + 1) * step;

                    for (int x = updateLeft; x <= updateRight; x += step)
                    {
                        for (int y = updateTop; y <= updateBottom; y += step)
                        {
                            int n = (x / step) + (y / step) * width;
                            var str = (n % 99).ToString();

                            ds.DrawText(str, x, y, Colors.White, format);
                            drawTextCalls++;
                        }
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                // Ignore device lost errors; ultimately, the control will be notified that surfaces have been lost and will call OnCreateResources
                switch ((uint)e.HResult)
                {
                    case 0x887A0006: // DXGI_ERROR_DEVICE_HUNG
                    case 0x887A0005: // DXGI_ERROR_DEVICE_REMOVED
                    case 0x887A0007: // DXGI_ERROR_DEVICE_RESET
                    case 0x887A0020: // DXGI_ERROR_DRIVER_INTERNAL_ERROR
                        break;
                    default:
                        throw;
                }
            }

            status.Text = string.Format("There were {0} DrawText() calls on last update", drawTextCalls);
        }
Exemplo n.º 12
0
        static Statics()
        {
            DefaultFont = new CanvasTextFormat();
            DefaultFont.FontFamily = "Arial";
            DefaultFont.FontSize = 14;
            DefaultFont.WordWrapping = CanvasWordWrapping.Wrap; //.NoWrap;

            DefaultFontNoWrap = new CanvasTextFormat();
            DefaultFontNoWrap.FontFamily = "Arial";
            DefaultFontNoWrap.FontSize = 14;
            DefaultFontNoWrap.WordWrapping = CanvasWordWrapping.NoWrap; //.NoWrap;

            // CanvasTextLayout objects are initialized in CreateResources
        }
        public RichListBoxLeaderboard(CanvasDevice device, Vector2 position, int width, int height, string title, CanvasTextFormat titleFont, CanvasTextFormat stringsFont, CanvasTextFormat leadersFont)
            : base(device, position, width, height, title, titleFont, stringsFont, 0)
        {
            LeadersFont = leadersFont;

            // calculate leaders text layout (for text height)
            LeadersTextLayout = new CanvasTextLayout(device, "ABCDEFG", LeadersFont, 0, 0);

            // calculate leaders position Y (X is calculated for each string)
            LeadersPosition = new Vector2(StringsPosition.X, StringsPosition.Y);

            // leaders position is dynamic
            // strings position is dynamic

            MaxY = (int)Position.Y + Height - Padding;
        }
Exemplo n.º 14
0
        public MainPage() {
            this.InitializeComponent();

            polarFix = (float)Math.PI / 2; // Polar coordinates starts at 0, puts the start of the pointers at
                                           // PI/2
            ray = (float)pane.ActualWidth; // Default ray, to be replaced when a layout changed event happens

            // A 2D vector pointing to the middle of the device screen.
            midScreen = new Vector2() {
                X = (float)pane.ActualWidth / 2,
                Y = (float)pane.ActualHeight / 2
            };

            font = new CanvasTextFormat() {
                FontSize = 10,
                FontFamily = "Times New Roman"
            };
        }
        void canvas_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
        {
            // Create the Direct3D teapot model.
            teapot = new TeapotRenderer(sender);

            // Create Win2D resources for drawing the scrolling text.
            var textFormat = new CanvasTextFormat
            {
                FontSize = fontSize,
                HorizontalAlignment = CanvasHorizontalAlignment.Center
            };

            textLayout = new CanvasTextLayout(sender, scrollingText, textFormat, textRenderTargetSize - textMargin * 2, float.MaxValue);

            textRenderTarget = new CanvasRenderTarget(sender, textRenderTargetSize, textRenderTargetSize);

            // Set the scrolling text rendertarget (a Win2D object) as
            // source texture for our 3D teapot model (which uses Direct3D).
            teapot.SetTexture(textRenderTarget);
        }
        public RichListBoxProminent(CanvasDevice device, Vector2 position, int width, string title, CanvasTextFormat titleFont, int maxStrings, CanvasTextFormat stringsFont, CanvasTextFormat prominentStringFont)
            : base(device, position, width, 0, title, titleFont, stringsFont, maxStrings)
        {
            // strings height
            double dStringsHeight = StringsTextLayout.LayoutBounds.Height * (MaxStrings - 1);

            // bar under strings
            BarUnderStringsLeft = new Vector2(Position.X, StringsPosition.Y + (float)dStringsHeight + Padding);
            BarUnderStringsRight = new Vector2(Position.X + Width, StringsPosition.Y + (float)dStringsHeight + Padding);

            // prominent string
            ProminentStringPosition = new Vector2(Position.X + Padding, BarUnderStringsRight.Y + Padding);
            ProminentStringFont = prominentStringFont;
            ProminentStringLayout = new CanvasTextLayout(device, "THIS IS A PRETTY GOOD TEMP STRING", ProminentStringFont, 0, 0);

            // total height
            Height = (int)(Title.LayoutBounds.Height + Padding * 6 + dStringsHeight + ProminentStringLayout.LayoutBounds.Height);

            // border
            BorderRectangle = new Rect(Position.X, Position.Y, Width, Height);
        }
        private async void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var textblock = sender as TextBlock;
            utextblock = new UniversalElement(sender);

            var textformat = new CanvasTextFormat()
            {
                FontFamily = textblock.FontFamily.Source,
                FontSize = (float)textblock.FontSize,
                FontStretch = textblock.FontStretch,
                FontWeight = textblock.FontWeight
            };

            var textlayout = new CanvasTextLayout(utextblock.Masker.Device, textblock.Text, textformat, (float)textblock.ActualWidth + 6, (float)textblock.ActualHeight + 6);

            var geometry = CanvasGeometry.CreateText(textlayout);

            await utextblock.CreateMaskBrush(geometry.Stroke(3), Colors.Blue);

            var first = (utextblock.Element.Parent as Panel).Children.First();
            ElementCompositionPreview.SetElementChildVisual(first, utextblock.Visual);
        }
 private void DrawElement(TextRender2MeasureMapElement element, CanvasDrawingSession session, Rect region)
 {
     var command = element.Command;
     string text;
     var textCnt = command.Content as ITextRenderTextContent;
     if (textCnt != null)
     {
         text = textCnt.Text ?? "";
     }
     else
     {
         text = "";
     }
     using (var format = new CanvasTextFormat())
     {
         format.FontFamily = "Segoe UI";
         format.FontSize = (float)Callback.PostFontSize;
         format.WordWrapping = CanvasWordWrapping.NoWrap;
         format.TrimmingGranularity = CanvasTextTrimmingGranularity.None;
         format.HorizontalAlignment = CanvasHorizontalAlignment.Left;
         session.DrawText(text, new Vector2((float)element.Placement.X, (float)element.Placement.Y), Colors.Black, format);
     }
 }
Exemplo n.º 19
0
        private CanvasTextLayout CreateTextLayout(ICanvasResourceCreator resourceCreator, float canvasWidth, float canvasHeight)
        {
            float sizeDim = Math.Min(canvasWidth, canvasHeight);

            CanvasTextFormat textFormat;
            switch (CurrentTextSampleOption)
            {
                case TextSampleOption.QuickBrownFox:
                    testString = "The quick brown fox jumps over the lazy dog.";
                    textFormat = new CanvasTextFormat()
                    {
                        FontSize = sizeDim * 0.1f,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        VerticalAlignment = CanvasVerticalAlignment.Center
                    };
                    break;

                case TextSampleOption.LatinLoremIpsum:
                    testString = @"                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer lacinia odio lectus, eget luctus felis tincidunt sit amet. Maecenas vel ex porttitor, ultrices nunc feugiat, porttitor quam. Cras non interdum urna. In sagittis tempor leo quis laoreet. Sed pretium tellus ut commodo viverra. Ut volutpat in risus at aliquam. Sed faucibus vitae dolor ut commodo.
                    Mauris mollis rhoncus libero ut porttitor. Suspendisse at egestas nunc. Proin non neque nibh. Mauris eu ornare arcu. Etiam non sem eleifend, imperdiet erat at, hendrerit ante. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer porttitor mauris eu pulvinar commodo. Interdum et malesuada fames ac ante ipsum primis in faucibus.
                    Mauris ultricies fermentum sem sed consequat. Vestibulum iaculis dui nulla, nec pharetra dolor gravida in. Pellentesque vel nisi urna. Donec gravida nunc sed pellentesque feugiat. Aliquam iaculis enim non enim ultrices aliquam. In at leo sed lorem interdum bibendum at non enim. Vivamus fermentum nisl eros, sit amet laoreet justo tincidunt et. Maecenas nunc erat, placerat non efficitur quis, convallis et nunc. Integer eget nunc id nunc convallis hendrerit. Mauris ac ornare nibh, vel condimentum dolor. Nullam dictum nibh eget tempus suscipit. Sed in ligula vitae ligula dignissim semper vel pretium nisl. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
                    Cras sit amet pretium libero. Maecenas non mauris vitae ante auctor hendrerit. Donec ut felis metus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus sodales commodo imperdiet. Vestibulum maximus diam ac dui rhoncus blandit. Curabitur id tincidunt urna. Vivamus vitae blandit sem. Duis non sem nibh. Proin a lacus ac est egestas aliquam in vel dolor. Duis semper mattis elit, vitae bibendum lacus tempus vel. Quisque eget ultrices orci, id sagittis est. Duis fringilla pretium diam, at finibus ex elementum vel. Aenean nibh lectus, consequat nec libero interdum, gravida vestibulum mi.
                    Etiam arcu libero, semper et maximus eget, mollis in dui. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer hendrerit neque non libero rutrum tincidunt. Fusce in odio vel nisl aliquam tempus. Fusce sollicitudin nisi vel eros consequat, ac pulvinar lorem imperdiet. Aliquam pulvinar metus sed varius porta. Curabitur ac leo laoreet, bibendum erat sit amet, pulvinar purus. Sed laoreet ipsum eu tortor congue vulputate. Integer convallis vulputate urna. Nulla quis vestibulum justo. Vestibulum non purus nunc.";

                    textFormat = new CanvasTextFormat()
                    {
                        FontSize = sizeDim * 0.025f,
                        HorizontalAlignment = CanvasHorizontalAlignment.Left,
                        VerticalAlignment = CanvasVerticalAlignment.Top
                    };
                    break;

                case TextSampleOption.乱数假文:
                default:
                    testString = "不結邊的聲不陸還下絕去以得一票來夠年維書:原有馬下,不時不去遊制日經養投外光、調預知拉越位;去進就管一率客於行小眾一關金的相。現的一展己明物程上益驚,步使超友究比質管日。散奇說。有急理裝臺也足報國發,院來自加樂為?應報心境好調怕銀利的器理濟生他,地人知滿提球術不先表……值想不為品華信子會他過知天清與止為的。實時知嚴怕傳著配法類加,點展源又上後吸上戲上上的不當。一種人利取過微家品領不作出得那、確他他如樂德的,活布還理收,高子許臺輪電性跑整想水功用通。大雙小分過排現令簡。公方要排題公排見教去。終後少!口許一此表自無人……種活構自動一些林、切、師是放不注!氣以那中以新統雖這水?名標天。每利出、帶未心時我斷有看系是士,道此我地技一平水大非我意然,現了。它好作下物失不感一,適事資清有足收不推行……館臺卻告下、動論然中率麼說裡了本大解事成先文如。可再冷自們。一為何。史地著,證政科、展言用往。";

                    textFormat = new CanvasTextFormat()
                    {
                        FontSize = sizeDim * 0.04f,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center,
                        VerticalAlignment = CanvasVerticalAlignment.Center,
                        Direction = CanvasTextDirection.TopToBottomThenRightToLeft
                    };
                    break;
            }

            textFormat.FontFamily = fontPicker.CurrentFontFamily;

            textFormat.TrimmingGranularity = CanvasTextTrimmingGranularity.Word;
            textFormat.TrimmingSign = UseEllipsisTrimming ? CanvasTrimmingSign.Ellipsis : CanvasTrimmingSign.None;

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

            return textLayout;
        }
Exemplo n.º 20
0
        private ICanvasImage CreateNotSupportedMessage(string message)
        {
            var commandList = new CanvasCommandList(canvas);

            var textFormat = new CanvasTextFormat
            {
                FontSize = 16,
                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                VerticalAlignment = CanvasVerticalAlignment.Center
            };

            using (var ds = commandList.CreateDrawingSession())
            {
                ds.DrawText(message, bitmapTiger.Bounds, Colors.Red, textFormat);
            }

            animationFunction = elapsedTime => { };

            return commandList;
        }
Exemplo n.º 21
0
        private void DrawPage(CanvasPrintDocument sender, CanvasDrawingSession ds, uint pageNumber, Rect imageableRect)
        {
            var cellAcross = new Vector2(cellSize.X, 0);
            var cellDown = new Vector2(0, cellSize.Y);

            var totalSize = cellAcross * columns + cellDown * rows;
            Vector2 topLeft = (pageSize - totalSize) / 2;

            int bitmapIndex = ((int)pageNumber - 1) * bitmapsPerPage;

            var labelFormat = new CanvasTextFormat()
            {
                FontFamily = "Comic Sans MS",
                FontSize = 12,
                VerticalAlignment = CanvasVerticalAlignment.Bottom,
                HorizontalAlignment = CanvasHorizontalAlignment.Left
            };

            var numberFormat = new CanvasTextFormat()
            {
                FontFamily = "Comic Sans MS",
                FontSize = 18,
                VerticalAlignment = CanvasVerticalAlignment.Top,
                HorizontalAlignment = CanvasHorizontalAlignment.Left
            };

            var pageNumberFormat = new CanvasTextFormat()
            {
                FontFamily = "Comic Sans MS",
                FontSize = 10,
                VerticalAlignment = CanvasVerticalAlignment.Bottom,
                HorizontalAlignment = CanvasHorizontalAlignment.Center
            };

            var titleFormat = new CanvasTextFormat()
            {
                FontFamily = "Comic Sans MS",
                FontSize = 24,
                VerticalAlignment = CanvasVerticalAlignment.Top,
                HorizontalAlignment = CanvasHorizontalAlignment.Left
            };


            if (pageNumber == 1)
                ds.DrawText("Win2D Printing Example", imageableRect, Colors.Black, titleFormat);

            ds.DrawText(string.Format("Page {0} / {1}", pageNumber, pageCount),
                imageableRect,
                Colors.Black,
                pageNumberFormat);

            DrawGrid(ds, cellAcross, cellDown, topLeft);

            for (int row = 0; row < rows; ++row)
            {
                for (int column = 0; column < columns; ++column)
                {
                    var cellTopLeft = topLeft + (cellAcross * column) + (cellDown * row);

                    var paddedTopLeft = cellTopLeft + textPadding / 2;
                    var paddedSize = cellSize - textPadding;

                    var bitmapInfo = bitmaps[bitmapIndex % bitmaps.Count];

                    // Center the bitmap in the cell
                    var bitmapPos = cellTopLeft + (cellSize - bitmapInfo.Bitmap.Size.ToVector2()) / 2;

                    ds.DrawImage(bitmapInfo.Bitmap, bitmapPos);

                    using (var labelLayout = new CanvasTextLayout(sender, bitmapInfo.Name, labelFormat, paddedSize.X, paddedSize.Y))
                    using (var numberLayout = new CanvasTextLayout(sender, (bitmapIndex + 1).ToString(), numberFormat, paddedSize.X, paddedSize.Y))
                    {
                        DrawTextOverWhiteRectangle(ds, paddedTopLeft, labelLayout);
                        DrawTextOverWhiteRectangle(ds, paddedTopLeft, numberLayout);
                    }

                    bitmapIndex++;
                }
            }
        }
Exemplo n.º 22
0
 internal override void setFont(Microsoft.Graphics.Canvas.Text.CanvasTextFormat font)
 {
     this.font = font;
 }
Exemplo n.º 23
0
        static void DrawTile(CanvasDrawingSession ds, float width, float height)
        {
            using (var cl = new CanvasCommandList(ds))
            {
                using (var clds = cl.CreateDrawingSession())
                {
                    var text = string.Format("{0}\n{1}", DateTime.Now.ToString("ddd"), DateTime.Now.ToString("HH:mm"));

                    var textFormat = new CanvasTextFormat()
                    {
                        FontFamily = "Segoe UI Black",
                        HorizontalAlignment = CanvasHorizontalAlignment.Right,
                        VerticalAlignment = CanvasVerticalAlignment.Center,
                        FontSize = 20,
                        LineSpacing = 20
                    };

                    clds.DrawText(text, 0, 0, Colors.White, textFormat);
                }

                var effect = new GaussianBlurEffect()
                {
                    Source = cl,
                    BlurAmount = 1,
                };

                ds.Clear(Colors.Orange);

                var bounds = effect.GetBounds(ds);
                var ratio = bounds.Height / bounds.Width;
                var destHeight = height * ratio;

                ds.DrawImage(effect, new Rect(0, height / 2 - destHeight / 2, width, destHeight), bounds);

                ds.DrawText(string.Format("Generated by Win2D\n{0}\n{1}", DateTime.Now.ToString("d"), DateTime.Now.ToString("t")),
                    12, 12, Colors.Black,
                    new CanvasTextFormat()
                    {
                        HorizontalAlignment = CanvasHorizontalAlignment.Left,
                        VerticalAlignment = CanvasVerticalAlignment.Top,
                        FontSize = 12
                    });
            }
        }
Exemplo n.º 24
0
 internal virtual void setFont(CanvasTextFormat font)
 {
     this.font = font;
     //font.FontFamily = "Arial";
 }
Exemplo n.º 25
0
            void Label(CanvasDrawingSession ds, float x, float y, string text)
            {
                var textFormat = new CanvasTextFormat()
                {
                    FontSize = 16,
                    HorizontalAlignment = CanvasHorizontalAlignment.Center,
                    VerticalAlignment = CanvasVerticalAlignment.Bottom
                };

                ds.DrawText(text, x + 128, y + 256 - 16, Colors.White, textFormat);
            }
Exemplo n.º 26
0
            CanvasTextLayout MakeLabel(CanvasDrawingSession ds, string text, float halfWidth)
            {
                var format = new CanvasTextFormat()
                {
                    FontSize = 14,
                    HorizontalAlignment = CanvasHorizontalAlignment.Right,
                    VerticalAlignment = CanvasVerticalAlignment.Center
                };

                return new CanvasTextLayout(ds, text, format, halfWidth, 64);
            }
Exemplo n.º 27
0
            public void Draw(CanvasDrawingSession ds, int frameCounter, float width, float height)
            {
                var sz = sourceBitmap.Size;
                Rect sourceRect = new Rect(
                    sz.Width * 0.25 + Math.Sin(frameCounter * 0.02) * (sz.Width * 0.5),
                    sz.Height * 0.25 + Math.Cos(frameCounter * 0.01) * (sz.Height * 0.5),
                    sz.Width * 0.5,
                    sz.Height * 0.5);

                double y = DrawSourceImage(ds, sourceRect, width);

                double displayWidth = width / 2;
                double x = displayWidth;
                double destHeight = (height - y) / 3;

                Rect bitmapDestRect = new Rect(x, y + 5, displayWidth, destHeight - 10);
                y += destHeight;

                Rect bitmapDestRect2 = new Rect(x, y + 5, displayWidth, destHeight - 10);
                y += destHeight;

                Rect effectDestRect = new Rect(x, y + 5, displayWidth, destHeight - 10);

                var format = new CanvasTextFormat()
                {
                    FontSize = 14,
                    HorizontalAlignment = CanvasHorizontalAlignment.Right,
                    VerticalAlignment = CanvasVerticalAlignment.Center
                };

                ds.DrawText("D2D DrawBitmap", 0, (float)bitmapDestRect.Y, (float)displayWidth - 10, (float)destHeight, Colors.White, format);
                ds.DrawText("D2D DrawImage (bitmap)", 0, (float)bitmapDestRect2.Y, (float)displayWidth - 10, (float)destHeight, Colors.White, format);
                ds.DrawText("D2D DrawImage (effect)", 0, (float)effectDestRect.Y, (float)displayWidth - 10, (float)destHeight, Colors.White, format);

                ds.FillRectangle(bitmapDestRect, fillPattern);
                ds.FillRectangle(bitmapDestRect2, fillPattern);
                ds.FillRectangle(effectDestRect, fillPattern);

                ds.DrawImage(sourceBitmap, bitmapDestRect, sourceRect);
                ds.DrawImage(sourceBitmap, bitmapDestRect2, sourceRect, 1, CanvasImageInterpolation.Cubic);
                ds.DrawImage(sourceEffect, effectDestRect, sourceRect);

                ds.DrawRectangle(bitmapDestRect, Colors.Yellow, 1, hairline);
                ds.DrawRectangle(bitmapDestRect2, Colors.Yellow, 1, hairline);
                ds.DrawRectangle(effectDestRect, Colors.Yellow, 1, hairline);
            }
Exemplo n.º 28
0
        private CanvasTextLayout CreateTextLayout(ICanvasResourceCreator resourceCreator, float canvasWidth, float canvasHeight)
        {
            string testString;

            if (CurrentTextLengthOption == TextLengthOption.Short)
            {
                testString = "one two";
            }
            else
            {
                testString = "This is some text which demonstrates Win2D's text-to-geometry option; there are sub-options of this test which apply lining options such as underline or strike-through. Additionally,  this example applies different text directions to ensure glyphs are transformed correctly.";
            }

            if(ThumbnailGenerator.IsDrawingThumbnail)
            {
                testString = "a";
            }

            for (int i = 0; i < testString.Length; ++i)
            {
                if (testString[i] == ' ')
                {
                    int nextSpace = testString.IndexOf(' ', i + 1);
                    int limit = nextSpace == -1 ? testString.Length : nextSpace;

                    WordBoundary wb = new WordBoundary();
                    wb.Start = i + 1;
                    wb.Length = limit - i - 1;
                    everyOtherWordBoundary.Add(wb);
                    i = limit;
                }
            }

            float sizeDim = Math.Min(canvasWidth, canvasHeight);

            CanvasTextFormat textFormat = new CanvasTextFormat()
            {
                FontSize = CurrentTextLengthOption == TextLengthOption.Paragraph? sizeDim * 0.09f : sizeDim * 0.3f,
                Direction = CurrentTextDirection,
            };

            if (ThumbnailGenerator.IsDrawingThumbnail)
            {
                textFormat.FontSize = sizeDim * 0.75f;
            }

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

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

            textLayout.VerticalGlyphOrientation = CurrentVerticalGlyphOrientation;

            return textLayout;
        }
Exemplo n.º 29
0
        private CanvasTextLayout CreateTextLayout(ICanvasResourceCreator resourceCreator, Size size)
        {
            var format = new CanvasTextFormat()
            {
                HorizontalAlignment = GetCanvasHorizontalAlignemnt(),
                VerticalAlignment = GetCanvasVerticalAlignment()
            };

            return new CanvasTextLayout(
                resourceCreator,
                Text,
                format,
                (float)size.Width,
                (float)size.Height);
        }
Exemplo n.º 30
0
            public Labeler(float f, float sd, Vector2 l, Rect tlb, float b, FontMetricsHolder.Metrics m, CanvasDrawingSession ds)
            {
                fontSize = f;
                sizeDim = sd;
                layoutSize = l;
                textLayoutBounds = tlb;
                baselineInWorldSpace = b;
                glyphRunMetrics = m;
                drawingSession = ds;

                horizontalMidpoint = (layoutSize.X / 2);

                leftJustifiedTextFormat = new CanvasTextFormat()
                {
                    VerticalAlignment = CanvasVerticalAlignment.Top,
                    HorizontalAlignment = CanvasHorizontalAlignment.Left
                };
                rightJustifiedTextFormat = new CanvasTextFormat()
                {
                    VerticalAlignment = CanvasVerticalAlignment.Top,
                    HorizontalAlignment = CanvasHorizontalAlignment.Right
                };

                NextLabel();
            }
Exemplo n.º 31
0
        static public CompositionDrawingSurface LoadText(string text, Size sizeTarget, CanvasTextFormat textFormat, Color textColor, Color bgColor)
        {
            Debug.Assert(_intialized);

            CompositionDrawingSurface surface = _compositionDevice.CreateDrawingSurface(sizeTarget,
                                                            DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            using (var ds = CanvasComposition.CreateDrawingSession(surface))
            {
                ds.Clear(bgColor);
                ds.DrawText(text, new Rect(0, 0, sizeTarget.Width, sizeTarget.Height), textColor, textFormat);
            }

            return surface;
        }
Exemplo n.º 32
0
            public void Draw(CanvasDrawingSession ds, int frameCounter, float width, float height)
            {
                Size sz = sourceBitmap.Size;

                double sourceSizeScale = (Math.Sin(frameCounter * 0.03) * 0.3) + 0.7;

                Point center = new Point(Math.Sin(frameCounter * 0.02), (Math.Cos(frameCounter * 0.01)));

                center.X *= (1 - sourceSizeScale) * sz.Width * 0.5;
                center.Y *= (1 - sourceSizeScale) * sz.Height * 0.5;

                center.X += sz.Width * 0.5;
                center.Y += sz.Height * 0.5;

                Rect sourceRect = new Rect(
                    center.X - sz.Width * sourceSizeScale * 0.5,
                    center.Y - sz.Height * sourceSizeScale * 0.5,
                    sz.Width * sourceSizeScale,
                    sz.Height * sourceSizeScale);
                
                UpdateSourceRectRT(sourceRect);

                var format = new CanvasTextFormat()
                {
                    FontSize = 14,
                    HorizontalAlignment = CanvasHorizontalAlignment.Right,
                    VerticalAlignment = CanvasVerticalAlignment.Center,
                    WordWrapping = CanvasWordWrapping.Wrap
                };

                float y = 0;
                float labelX = width / 2 - 5;
                float imageX = width / 2 + 5;
                float entryHeight = (float)sourceBitmap.Bounds.Height;
                float margin = 14;

                Rect labelRect = new Rect(0, y, labelX, entryHeight);

                ds.DrawText(string.Format("Source image {0} DPI", sourceBitmap.Dpi), labelRect, Colors.White, format);
                ds.FillRectangle(imageX, y, (float)sz.Width, (float)sz.Height, fillPattern);
                ds.DrawImage(showSourceRectRT, imageX, y, showSourceRectRT.Bounds, 1, CanvasImageInterpolation.NearestNeighbor);

                y += entryHeight + margin;
                labelRect.Y = y;

                ds.DrawText("D2D DrawBitmap (emulated dest rect)", labelRect, Colors.White, format);
                ds.FillRectangle(imageX, y, (float)sz.Width, (float)sz.Height, fillPattern);
                ds.DrawImage(sourceBitmap, imageX, y, sourceRect);
                
                y += (float)sourceBitmap.Bounds.Height + 14;
                labelRect.Y = y;

                ds.DrawText("D2D DrawImage", labelRect, Colors.White, format);
                ds.FillRectangle(imageX, y, (float)sz.Width, (float)sz.Height, fillPattern);
                ds.DrawImage(sourceEffect, imageX, y, sourceRect);

            }