Exemplo n.º 1
1
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            using (var stream = await Root.RenderToRandomAccessStream())
            {
                var device = new CanvasDevice();
                var bitmap = await CanvasBitmap.LoadAsync(device, stream);

                var renderer = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, bitmap.Dpi);

                using (var ds = renderer.CreateDrawingSession())
                {
                    var blur = new GaussianBlurEffect();
                    blur.BlurAmount = 5.0f;
                    blur.Source = bitmap;
                    ds.DrawImage(blur);
                }

                stream.Seek(0);
                await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png);

                BitmapImage image = new BitmapImage();
                image.SetSource(stream);
                Blured.Source = image;
            }
        }
Exemplo n.º 2
0
		public byte[] DrawStrokeOnImageBackground(IReadOnlyList<InkStroke> strokes, byte[] backgroundImageBuffer)
		{

			var stmbuffer = new InMemoryRandomAccessStream();
			stmbuffer.AsStreamForWrite().AsOutputStream().WriteAsync(backgroundImageBuffer.AsBuffer()).AsTask().Wait();

			CanvasDevice device = CanvasDevice.GetSharedDevice();
			var canbit = CanvasBitmap.LoadAsync(device, stmbuffer, 96).AsTask().Result;


			CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, canbit.SizeInPixels.Width, canbit.SizeInPixels.Height, 96);

			using (var ds = renderTarget.CreateDrawingSession())
			{
				ds.Clear(Colors.Transparent);

				if (backgroundImageBuffer != null)
				{

					ds.DrawImage(canbit);
				}

				ds.DrawInk(strokes);
			}
			var stm = new InMemoryRandomAccessStream();
			renderTarget.SaveAsync(stm, CanvasBitmapFileFormat.Png).AsTask().Wait();
			var readfrom = stm.GetInputStreamAt(0).AsStreamForRead();
			var ms = new MemoryStream();
			readfrom.CopyTo(ms);
			var outputBuffer = ms.ToArray();
			return outputBuffer;
		}
    public async static Task<Uri> ToQrDataUri(this ISdp sdp, int width, int height)
    {
      var qrCodeWriter = new QRCodeWriter();
      var bitMatrix = qrCodeWriter.encode(sdp.ToString(), ZXing.BarcodeFormat.QR_CODE, width, height);

      using (var canvasRenderTarget = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), 500, 500, 96))
      {
        using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
        {
          for (var y = 0; y < height; y++)
          {
            for (var x = 0; x < width; x++)
            {
              drawingSession.DrawRectangle(x, y, 1, 1, bitMatrix.get(x, y) ? Color.FromArgb(0, 0, 0, 0) : Color.FromArgb(255, 255, 255, 255));
            }
          }
        }

        using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream())
        {
          await canvasRenderTarget.SaveAsync(inMemoryRandomAccessStream, CanvasBitmapFileFormat.Png);
          inMemoryRandomAccessStream.Seek(0);
          var buffer = new byte[inMemoryRandomAccessStream.Size];
          await inMemoryRandomAccessStream.ReadAsync(buffer.AsBuffer(), (uint)inMemoryRandomAccessStream.Size, InputStreamOptions.None);
          return new Uri($"data:image/png;base64,{Convert.ToBase64String(buffer)}");
        }
      }
    }
Exemplo n.º 4
0
        async void mainCanvas_CreateResources(Microsoft.Graphics.Canvas.CanvasControl sender, object args)
        {
            m_isResourceLoadingDone = false;

            // WIN2D: resource loading from WinRT types including StorageFile and IRAS
            m_sourceBitmap = await CanvasBitmap.LoadAsync(sender, "Chrysanthemum.jpg");
            var sourceFile = await Package.Current.InstalledLocation.GetFileAsync("Chrysanthemum.jpg");

            // Win2D: because we can't lock/read pixels we rely on BitmapDecoder
            var stream = await sourceFile.OpenReadAsync();
            var decoder = await BitmapDecoder.CreateAsync(stream);

            // Technically these should always be identical to m_sourceBitmap.SizeInPixels;
            m_pixelArrayHeight = decoder.PixelHeight;
            m_pixelArrayWidth = decoder.PixelWidth;
            var pixelProvider = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Premultiplied,
                new BitmapTransform(),
                ExifOrientationMode.IgnoreExifOrientation, // Must do this.
                ColorManagementMode.ColorManageToSRgb
                );

            m_pixelArray = pixelProvider.DetachPixelData();

            m_targetBitmap = new CanvasRenderTarget(sender, new Size(m_pixelArrayWidth, m_pixelArrayHeight));

            m_rnd = new Random();

            m_isResourceLoadingDone = true;

            mainCanvas.Invalidate();
        }
Exemplo n.º 5
0
        public async Task Save(StorageFile file)
        {
            var image = GetImage();

            // Measure the extent of the image (which may be cropped).
            Rect imageBounds;

            using (var commandList = new CanvasCommandList(sourceBitmap.Device))
            using (var drawingSession = commandList.CreateDrawingSession())
            {
                imageBounds = image.GetBounds(drawingSession);
            }

            // Rasterize the image into a rendertarget.
            using (var renderTarget = new CanvasRenderTarget(sourceBitmap.Device, (float)imageBounds.Width, (float)imageBounds.Height, 96))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    drawingSession.Blend = CanvasBlend.Copy;

                    drawingSession.DrawImage(image, -(float)imageBounds.X, -(float)imageBounds.Y);
                }

                // Save it out.
                var format = file.FileType.Equals(".png", StringComparison.OrdinalIgnoreCase) ? CanvasBitmapFileFormat.Png : CanvasBitmapFileFormat.Jpeg;

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    stream.Size = 0;

                    await renderTarget.SaveAsync(stream, format);
                }
            }
        }
Exemplo n.º 6
0
        public void MultithreadedSaveToFile()
        {
            //
            // This test can create a deadlock if the SaveAsync code holds on to the
            // ID2D1Multithread resource lock longer than necessary.
            //
            // A previous implementation waited until destruction of the IAsyncAction before calling Leave().  
            // In managed code this can happen on an arbitrary thread and so could result in deadlock situations
            // where other worker threads were waiting for a Leave on the original thread that never arrived.
            //

            using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called
            {
                var task = Task.Run(async () =>
                {
                    var device = new CanvasDevice();
                    var rt = new CanvasRenderTarget(device, 16, 16, 96);

                    var filename = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "testfile.jpg");

                    await rt.SaveAsync(filename);

                    rt.Dispose();
                });

                task.Wait();
            }
        }
        /// <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;
                    }
                }
            }
        }
 public ImageInfo(CanvasRenderTarget image, Point offset, Rect symbolBounds, Rect imageBounds)
 {
     _crt = image;
     _offset = offset;
     _symbolBounds = symbolBounds;
     _imageBounds = imageBounds;
 }
Exemplo n.º 9
0
 public void Process(CanvasBitmap input, CanvasRenderTarget output, TimeSpan time)
 {
     using (CanvasDrawingSession session = output.CreateDrawingSession())
     {
         session.DrawImage(input);
         session.DrawText("Canvas Effect test", 0f, 0f, Colors.Red);
     }
 }
 public void drawText(CanvasRenderTarget crt, Color color)
 {
     using (CanvasDrawingSession ds = crt.CreateDrawingSession())
     {
         ds.DrawTextLayout(textLayout, (float)location.X, (float)location.Y, color);
     }
        
 }
Exemplo n.º 11
0
        public void RecoverAfterDeviceLost()
        {
            if (cachedImage != null)
            {
                cachedImage.Dispose();
                cachedImage = null;
            }

            isCacheValid = false;
        }
Exemplo n.º 12
0
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="config"></param>
        private SSD1603(SSD1603Configuration config, BusTypes bus)
        {
            Configuration = config;
            BusType = bus;

            //for drawing
            _canvasDevice = CanvasDevice.GetSharedDevice();
            Render = new CanvasRenderTarget(_canvasDevice,  Screen.WidthInDIP, Screen.HeightInDIP, Screen.DPI,
                            Windows.Graphics.DirectX.DirectXPixelFormat.A8UIntNormalized, CanvasAlphaMode.Straight);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Applys a blur to a UI element
        /// </summary>
        /// <param name="sourceElement">UIElement to blur, generally an Image control, but can be anything</param>
        /// <param name="blurAmount">Level of blur to apply</param>
        /// <returns>Blurred UIElement as BitmapImage</returns>
        public static async Task<BitmapImage> BlurElementAsync(this UIElement sourceElement, float blurAmount = 2.0f)
        {
            if (sourceElement == null)
                return null;

            var rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(sourceElement);

            var buffer = await rtb.GetPixelsAsync();
            var array = buffer.ToArray();

            var displayInformation = DisplayInformation.GetForCurrentView();

            using (var stream = new InMemoryRandomAccessStream())
            {
                var pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Premultiplied,
                                     (uint) rtb.PixelWidth,
                                     (uint) rtb.PixelHeight,
                                     displayInformation.RawDpiX,
                                     displayInformation.RawDpiY,
                                     array);

                await pngEncoder.FlushAsync();
                stream.Seek(0);

                var canvasDevice = new CanvasDevice();
                var bitmap = await CanvasBitmap.LoadAsync(canvasDevice, stream);

                var renderer = new CanvasRenderTarget(canvasDevice,
                                                      bitmap.SizeInPixels.Width,
                                                      bitmap.SizeInPixels.Height,
                                                      bitmap.Dpi);

                using (var ds = renderer.CreateDrawingSession())
                {
                    var blur = new GaussianBlurEffect
                    {
                        BlurAmount = blurAmount,
                        Source = bitmap
                    };
                    ds.DrawImage(blur);
                }

                stream.Seek(0);
                await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png);

                var image = new BitmapImage();
                await image.SetSourceAsync(stream);

                return image;
            }
        }
 public ImageInfo(CanvasRenderTarget image)
 {
     _crt = image;
     BitmapSize bsize = image.SizeInPixels;
     Size size = image.Size;
     _offset = new Point(size.Width / 2.0f, size.Height / 2.0f);
     using (CanvasDrawingSession ds = image.CreateDrawingSession())
     {
         _symbolBounds = image.GetBounds(ds);
         _imageBounds = ShapeUtilities.clone(_symbolBounds);
     }
 }
Exemplo n.º 15
0
        public void RenderTargetInheritsDpiFromResourceCreator()
        {
            const float defaultDpi = 96;
            const float highDpi = 144;

            var device = new CanvasDevice();

            var renderTargetDefault = new CanvasRenderTarget(new TestResourceCreator(device, defaultDpi), 1, 1);
            var renderTargetHigh = new CanvasRenderTarget(new TestResourceCreator(device, highDpi), 1, 1);

            Assert.AreEqual(defaultDpi, renderTargetDefault.Dpi);
            Assert.AreEqual(highDpi, renderTargetHigh.Dpi);
        }
Exemplo n.º 16
0
 public void Process(CanvasBitmap input, CanvasRenderTarget output, TimeSpan time)
 {
     using (CanvasDrawingSession session = output.CreateDrawingSession())
     {
         session.DrawImage(input);
         session.FillCircle(
             (float)input.Bounds.Width / 2,
             (float)input.Bounds.Height / 2,
             (float)(Math.Min(input.Bounds.Width, input.Bounds.Height) / 2 * Math.Cos(2 * Math.PI * time.TotalSeconds)),
             Colors.Aqua
             );
     }
 }
        public void renderSVGPathToGraphics(CanvasRenderTarget crt)
        {
            /*
            //singlepoint graphic with absolute commands
            string path = "M1051 544L876 443L846 504L1018 600L1051 544ZM684 341L509 241L479 301L651 397L684 341ZM395 187L275 119L247 174L362 240L395 187ZM-833 -474L-1009 -568L-1038 -508L-864 -415L-833 -474ZM-237 -158L-411 -251L-439 -193L-271 -101L-237 -158ZM-533 -317L-709 -411L-739 -351L-567 -260L-533 -317ZM662 -399L514 -316L544 -263L690 -344L662 -399ZM-883 456L-1029 537L-999 592L-852 511L-883 456ZM992 -580L826 -488L859 -436L1021 -526L992 -580ZM-593 296L-748 382L-718 438L-566 350L-593 296ZM-305 137L-442 214L-415 268L-277 193L-305 137ZM381 -242L235 -161L272 -112L411 -188L381 -242ZM-210 -90L-111 -80Q-102 -130 -75 -153T-1 -176Q48 -176 73 -156T98 -107Q98 -89 88 -77T51 -55Q33 -49 -31 -33Q-112 -13 -145 17Q-191 58 -191 118Q-191 156 -170 189T-107 240T-8 258Q87 258 134 217T185 106L83 101Q77 140 56 157T-9 174Q-53 174 -78 156Q-94 144 -94 125Q-94 107 -79 94Q-60 78 14 61T123 25T179 -26T199 -107Q199 -150 175 -187T107 -243T-2 -262Q-98 -262 -149 -218T-210 -90Z";
            //singlepoint graphic with relative commands
            string pathLC = "M1051 544l-175 -101l-30 61l172 96zM684 341l-175 -100l-30 60l172 96zM395 187l-120 -68l-28 55l115 66zM-833 -474l-176 -94l-29 60l174 93zM-237 -158l-174 -93l-28 58l168 92zM-533 -317l-176 -94l-30 60l172 91zM662 -399l-148 83l30 53l146 -81zM-883 456l-146 81l30 55l147 -81zM992 -580l-166 92l33 52l162 -90zM-593 296l-155 86l30 56l152 -88zM-305 137l-137 77l27 54l138 -75zM381 -242l-146 81l37 49l139 -76zM-210 -90l98.999 10c6 -33.333 18.167 -57.666 36.5 -72.999s42.833 -23 73.5 -23c32.667 0 57.334 6.83301 74.001 20.5s25 29.834 25 48.501c0 12 -3.5 22.167 -10.5 30.5s-19.167 15.5 -36.5 21.5c-12 4 -39.333 11.333 -82 22c-54 13.333 -92 30 -114 50c-30.667 27.333 -46 61 -46 101c0 25.333 7.16699 49.166 21.5 71.499s35.166 39.333 62.499 51s60.333 17.5 99 17.5c63.333 0 110.833 -13.833 142.5 -41.5s48.5 -64.5 50.5 -110.5l-102 -5c-4 26 -13.167 44.667 -27.5 56s-35.833 17 -64.5 17c-29.333 0 -52.333 -6 -69 -18c-10.667 -8 -16 -18.333 -16 -31c0 -12 5 -22.333 15 -31c12.667 -10.667 43.667 -21.834 93 -33.501s85.833 -23.667 109.5 -36s42.167 -29.333 55.5 -51s20 -48.5 20 -80.5c0 -28.667 -8 -55.5 -24 -80.5s-38.667 -43.667 -68 -56s-65.666 -18.5 -108.999 -18.5c-64 0 -113 14.667 -147 44s-54.333 72 -61 128z";
            //the letter S
            string pathS = "M74 477L362 505Q388 360 467 292T682 224Q825 224 897 284T970 426Q970 478 940 514T833 578Q781 596 596 642Q358 701 262 787Q127 908 127 1082Q127 1194 190 1291T373 1440T662 1491Q938 1491 1077 1370T1224 1047L928 1034Q909 1147 847 1196T659 1246Q530 1246 457 1193Q410 1159 410 1102Q410 1050 454 1013Q510 966 726 915T1045 810T1207 661T1266 427Q1266 301 1196 191T998 28T679 -26Q401 -26 252 102T74 477Z";
            //air control point
            string pathACP = "M-355 354c-96.667 -97.333 -145 -215 -145 -353c0 -137.333 48.833 -254.666 146.5 -351.999s215.167 -146 352.5 -146c138 0 255.833 48.667 353.5 146s146.5 214.666 146.5 351.999c0 138 -48.5 255.667 -145.5 353s-215.167 146 -354.5 146 s-257.333 -48.667 -354 -146zM287.5 291c79.667 -80 119.498 -176.667 119.498 -290s-40.167 -210 -120.5 -290s-177.166 -120 -290.499 -120c-114 0 -211 40 -291 120s-120 176.667 -120 290s40 210 120 290s177 120 291 120c114.667 0 211.834 -40 291.501 -120zM-84.002 18h-47l-20 55h-89l-18 -55h-49l88 243h47zM-171.002 111l-29 86l-29 -86h58zM56.998 105l42.999 -15.999c-7.33301 -25.333 -18.666 -44.5 -33.999 -57.5s-34.333 -19.5 -57 -19.5c-29.333 0 -53.333 11 -72 33s-28 52 -28 90c0 40 9.66699 71.167 29 93.5 s44 33.5 74 33.5c26.667 0 48.334 -8.66699 65.001 -26c10 -10 17.667 -25 23 -45l-44 -12c-2.66699 13.333 -8.33398 23.666 -17.001 30.999s-18.334 11 -29.001 11c-16 0 -29 -6.66699 -39 -20s-15 -34 -15 -62c0 -30.667 4.83301 -52.667 14.5 -66s22.5 -20 38.5 -20 c10.667 0 20.334 4.33301 29.001 13s15 21.667 19 39zM126.997 18.001l0.000976562 242.998h72c27.333 0 45.333 -1.66699 54 -5c13.333 -2.66699 24.166 -10.167 32.499 -22.5s12.5 -28.166 12.5 -47.499c0 -15.333 -2.5 -28.166 -7.5 -38.499s-11.333 -18.333 -19 -24 s-15.5 -9.5 -23.5 -11.5c-10.667 -2 -26 -3 -46 -3h-30v-91h-45zM171.998 218.999v-68.999h25c18 0 30 1.16699 36 3.5s10.667 6.16602 14 11.499s5 12 5 20s-2.5 15 -7.5 21s-10.833 10 -17.5 12c-5.33301 0.666992 -16.333 1 -33 1h-22z";
            string AAMFrame = "M825 -750q-37 1143 -373 1519q-178 251 -452 281q-274 -30 -452 -283q-336 -374 -373 -1517h-129v168q9 1127 453 1560q248 228 501 232q253 -4 501 -232q444 -433 453 -1560v-168h-129z";
            string AAMFill = "M-866 -750q39 1200 391 1593q187 266 475 297q288 -31 475 -295q352 -395 391 -1595h-1732z";
            string AAMS1 = "M-182 -100h-88l-34 91h-162l-32 -91h-87l158 400h84zM-331 60l-57 145l-54 -145h111zM0 600l-110 -130v-745l-150 -95v-200l260 105l260 -105v200l-150 95v745zM588 -100h-88l-34 91h-162l-32 -91h-87l158 400h84zM439 60l-57 145l-54 -145h111zM70 440v-744l154 -89 v-122l-224 93l-224 -93v122l154 89v744l70 90z";
            string AAMS2 = "M70 440v-744l154 -89v-122l-224 93l-224 -93v122l154 89v744l70 90z";
            //string regex = 
            string[] parts = Regex.Split(path,_regex);

            foreach (String val in parts)
            {
                Debug.WriteLine(val);
            }
            Debug.WriteLine(_regex);

            SVGPath s = new SVGPath("0", pathACP);
            Color lineColor = (Colors.Black);
            Color fillColor = (Colors.Cyan);
            //Image foo = s.Draw(400,400,lineColor,fillColor);
            //g.DrawImage(foo, 200f, 200f);

            //Air to Air Missle test
            SVGPath sFill = new SVGPath("0",AAMFill);
            SVGPath sFrame = new SVGPath("0", AAMFrame);
            SVGPath sS1 = new SVGPath("0", AAMS1);
            SVGPath sS2 = new SVGPath("0", AAMS2);
            Image foo = sFrame.Draw(400, 400, lineColor, fillColor);
            crt.DrawImage(foo, 200f, 200f);

            //speed test
            int count = 1;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for(int k = 0; k < count; k++)
            {
                s = new SVGPath("0", path);
                s.Draw(60, 60, lineColor, fillColor);
            }
            sw.Stop();
            Debug.WriteLine("Rendered " + count.ToString() + " SP tactical graphics in " + Convert.ToString(sw.ElapsedMilliseconds / 1000.0) + " seconds.");
            //*/
        }
Exemplo n.º 18
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            var task = Task.Run(async () =>
            {
                var device = new CanvasDevice();
                var rt = new CanvasRenderTarget(device, 16, 16, 96);

                var stream = new MemoryStream();
                await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                rt.Dispose();
            });

            task.Wait();
        }
        //Creates textures of different sizes
        public void CreateParticleBitmaps(bool blur = false)
        {
            SetColors(baseColor);

            particleBitmaps = new CanvasRenderTarget[sizes];

            int i = -1;
            var nextRadius = 0;
            var nextSize =0;
            var transparent = Color.FromArgb(0, 0, 0, 0);

            float viewportsize = 100; //Here is the trick, if this value is too small appears the displacement and the original image

            for (int r = 1; r < sizes + 1; r += 1)
            {
                nextRadius = (r * minRadius);
                nextSize = nextRadius * 2;
                CanvasRenderTarget canvas = new CanvasRenderTarget(device, viewportsize, viewportsize, parent.Dpi);
                var center = new Vector2((viewportsize - nextRadius) / 2);

                //The following is like a 'drawing graph', the output of the first is the input of the second one;
                using (CanvasDrawingSession targetSession = canvas.CreateDrawingSession())
                {
                    targetSession.Clear(transparent);
                    targetSession.FillCircle(center, nextRadius, outerColor);
                    targetSession.FillCircle(center, nextRadius - 6, innerColor);
                }

                if (!blur)
                {
                    particleBitmaps[++i] = canvas;
                }
                else //Add blur just one time
                {
                    var blurEffect = new GaussianBlurEffect() { BlurAmount = 2f };
                    CanvasRenderTarget blurredcanvas = new CanvasRenderTarget(device, viewportsize, viewportsize, parent.Dpi);
                    blurEffect.Source = canvas;
                    using (CanvasDrawingSession targetSession = blurredcanvas.CreateDrawingSession())
                    {
                        targetSession.Clear(transparent);
                        targetSession.DrawImage(blurEffect);
                    }
                    particleBitmaps[++i] = blurredcanvas;
                }
            }
        }
Exemplo n.º 20
0
        public void RenderTargetDpiTest()
        {
            const float defaultDpi = 96;
            const float highDpi = defaultDpi * 2;
            const float size = 100;
            const float fractionalSize = 100.8f;

            var device = new CanvasDevice();

            var renderTargetDefault = new CanvasRenderTarget(device, size, size, defaultDpi);
            var renderTargetHigh = new CanvasRenderTarget(device, size, size, highDpi);
            var renderTargetFractionalSize = new CanvasRenderTarget(device, fractionalSize, fractionalSize, highDpi);

            // Check each rendertarget reports the expected DPI.
            Assert.AreEqual(defaultDpi, renderTargetDefault.Dpi);
            Assert.AreEqual(highDpi, renderTargetHigh.Dpi);
            Assert.AreEqual(highDpi, renderTargetFractionalSize.Dpi);

            // Check each rendertarget is of the expected size.
            Assert.AreEqual(size, renderTargetDefault.Size.Width);
            Assert.AreEqual(size, renderTargetDefault.Size.Height);

            Assert.AreEqual(size, renderTargetHigh.Size.Width);
            Assert.AreEqual(size, renderTargetHigh.Size.Height);

            Assert.AreEqual(Math.Round(fractionalSize), renderTargetFractionalSize.Size.Width);
            Assert.AreEqual(Math.Round(fractionalSize), renderTargetFractionalSize.Size.Height);

            // Check sizes in pixels.
            Assert.AreEqual(size, renderTargetDefault.SizeInPixels.Width);
            Assert.AreEqual(size, renderTargetDefault.SizeInPixels.Height);

            Assert.AreEqual(size * highDpi / defaultDpi, renderTargetHigh.SizeInPixels.Width);
            Assert.AreEqual(size * highDpi / defaultDpi, renderTargetHigh.SizeInPixels.Height);

            Assert.AreEqual(Math.Round(fractionalSize * highDpi / defaultDpi), renderTargetFractionalSize.SizeInPixels.Width);
            Assert.AreEqual(Math.Round(fractionalSize * highDpi / defaultDpi), renderTargetFractionalSize.SizeInPixels.Height);

            // Check that drawing sessions inherit the DPI of the rendertarget being drawn onto.
            var drawingSessionDefault = renderTargetDefault.CreateDrawingSession();
            var drawingSessionHigh = renderTargetHigh.CreateDrawingSession();

            Assert.AreEqual(defaultDpi, drawingSessionDefault.Dpi);
            Assert.AreEqual(highDpi, drawingSessionHigh.Dpi);
        }
Exemplo n.º 21
0
		public byte[] DrawStrokeOnSolidColorBackground(IReadOnlyList<InkStroke> strokes, int width, int height, Color color )
		{														 
			CanvasDevice device = CanvasDevice.GetSharedDevice();
			CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, width, height, 96);

			using (var ds = renderTarget.CreateDrawingSession())
			{
				ds.Clear(color);
				ds.DrawInk(strokes);
			}
			var stm = new InMemoryRandomAccessStream();
			renderTarget.SaveAsync(stm, CanvasBitmapFileFormat.Png).AsTask().Wait();
			var readfrom = stm.GetInputStreamAt(0).AsStreamForRead();
			var ms = new MemoryStream();
			readfrom.CopyTo(ms);
			var outputBuffer = ms.ToArray();
			return outputBuffer;
		}
Exemplo n.º 22
0
        public ICanvasImage Cache(Photo photo, ICanvasImage image, params object[] keys)
        {
            if (cachedImage == null)
            {
                cachedImage = new CanvasRenderTarget(photo.SourceBitmap.Device, photo.Size.X, photo.Size.Y, 96);
            }

            using (var drawingSession = cachedImage.CreateDrawingSession())
            {
                drawingSession.Blend = CanvasBlend.Copy;
                drawingSession.DrawImage(image);
            }

            isCacheValid = true;
            cacheKeys = keys;

            return cachedImage;
        }
        private async void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            StorageFolder storageFolder = KnownFolders.SavedPictures;
            var file = await storageFolder.CreateFileAsync("sample.jpg", CreationCollisionOption.ReplaceExisting);

            CanvasDevice device = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)MyInkCanvas.ActualWidth, (int)MyInkCanvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
                ds.DrawInk(MyInkCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);
            }
        }
Exemplo n.º 24
0
        private static async Task<CanvasBitmap> DownloadPng(CanvasDevice device, Uri uri)
        {
            try
            {
                return await CanvasBitmap.LoadAsync(device, await CachedData.GetRandomAccessStreamAsync(uri));
            }
            catch (FileNotFoundException)
            {
                var rt = new CanvasRenderTarget(device, 480, 360, 96);

                using (var ds = rt.CreateDrawingSession())
                {
                    ds.Clear(Colors.Transparent);
                    ds.DrawLine(0, 0, (float)rt.Size.Width, (float)rt.Size.Height, Colors.Black, 1);
                    ds.DrawLine(0, (float)rt.Size.Height, (float)rt.Size.Width, 0, Colors.Black, 1);
                }
                return rt;
            }
        }
        public Particle(int x, int y, int idxBitmap, float orientationx, float orientationy, CanvasRenderTarget source, float particlespeed = 0.25f, bool particlefall = false)
        {
            particleBitmap = idxBitmap;
            Radius = (particleBitmap + 1) * 4;
            X = x;
            Y = y;
            OrientationX = orientationx;
            OrientationY = orientationy;

            //Here is all the turbulence, without this is linear
            random = generator.Next(2, 50);
            factor = 0.7f * random / 10.0f;
            var octaves = generator.Next(1, 5);
            turbulence = new Transform2DEffect() { Source = new TurbulenceEffect() { Octaves = octaves } };
            displacement = new DisplacementMapEffect() { Source = source, Displacement = turbulence };

            speed = particlespeed;
            fall = particlefall;
        }
Exemplo n.º 26
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called
            {
                var task = Task.Run(async () =>
                {
                    var device = new CanvasDevice();
                    var rt = new CanvasRenderTarget(device, 16, 16, 96);

                    var stream = new MemoryStream();
                    await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                    rt.Dispose();
                });

                task.Wait();
            }
        }
Exemplo n.º 27
0
		private static void RendererImage(Stream stream, SvgImageRendererSettings settings)
		{
			var svg = settings.Document;
			var viewPort = svg.RootElement.ViewPort;
			if (!viewPort.HasValue) throw new ArgumentException(nameof(settings));

			var width = viewPort.Value.Width;
			var height = viewPort.Value.Height;
			var device = CanvasDevice.GetSharedDevice();
			using (var offScreen = new CanvasRenderTarget(device, width, height, settings.Scaling * 96.0F))
			{
				using (var renderer = new Win2dRenderer(offScreen, svg))
				using (var session = offScreen.CreateDrawingSession())
				{
					session.Clear(Colors.Transparent);
					renderer.Render(width, height, session);
				}
				offScreen.SaveAsync(stream.AsRandomAccessStream(), (CanvasBitmapFileFormat)settings.Format, settings.Quality).AsTask().GetAwaiter().GetResult();
			}
		}
        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);
        }
Exemplo n.º 29
0
            public async Task<SoftwareBitmap> RenderAsync(IEnumerable<InkStroke> inkStrokes, double width, double height)
            {
                var dpi = DisplayInformation.GetForCurrentView().LogicalDpi;
                try
                {
                    var renderTarget = new CanvasRenderTarget(_canvasDevice, (float)width, (float)height, dpi); using (renderTarget)
                    {
                        using (var drawingSession = renderTarget.CreateDrawingSession())
                        {
                            drawingSession.DrawInk(inkStrokes);
                        }

                        return await SoftwareBitmap.CreateCopyFromSurfaceAsync(renderTarget);
                    }
                }
                catch (Exception e) when (_canvasDevice.IsDeviceLost(e.HResult))
                {
                    _canvasDevice.RaiseDeviceLost();
                }

                return null;
            }
            void DoTest(float opacity, CanvasBitmap source, CanvasRenderTarget target)
            {
                using (var ds = target.CreateDrawingSession())
                {
                    ds.FillRectangle(target.Bounds, fillPattern);

                    var leftHalf = source.Bounds;
                    leftHalf.Width /= 2;

                    var rightHalf = source.Bounds;
                    rightHalf.Width /= 2;
                    rightHalf.X     += rightHalf.Width;

                    // This version calls D2D DrawBitmap
                    ds.DrawImage(source, 0, 0, leftHalf, opacity, CanvasImageInterpolation.Linear);

                    // This version calls D2D DrawImage with emulated opacity
                    ds.DrawImage(source, (float)rightHalf.X, 0, rightHalf, opacity, CanvasImageInterpolation.Cubic);

                    ds.Antialiasing = CanvasAntialiasing.Aliased;
                    ds.DrawLine((float)rightHalf.X, 0, (float)rightHalf.X, (float)rightHalf.Height, Colors.Black, 1, hairline);
                }
            }
Exemplo n.º 31
0
        /// <summary>
        ///  Loads a <see cref="CanvasBitmap"/> from an XElement.
        /// </summary>
        /// <param name="canvasResource"> The canvas-resource. </param>
        /// <param name="element"> The source XElement. </param>
        /// <returns> The loaded <see cref="CanvasBitmap"/>. </returns>
        public static CanvasBitmap LoadBitmap(ICanvasResourceCreatorWithDpi canvasResource, XElement element)
        {
            int width = 1024, height = 1024;

            if (element.Element("PixelWidth") is XElement pixelWidth)
            {
                width = (int)pixelWidth;
            }
            if (element.Element("PixelHeight") is XElement pixelHeight)
            {
                height = (int)pixelHeight;
            }
            CanvasRenderTarget bitmap = new CanvasRenderTarget(canvasResource, width, height);

            if (element.Element("PixelBytes") is XElement pixelBytes)
            {
                string strings = pixelBytes.Value;
                byte[] bytes   = Convert.FromBase64String(strings);
                bitmap.SetPixelBytes(bytes);
            }

            return(null);
        }
        private async Task <MediaClip> CreateMediaClip(TimeSpan originalDuration)
        {
            var rendertargetBitmap = new RenderTargetBitmap();
            await rendertargetBitmap.RenderAsync(control);

            var bfr = await rendertargetBitmap.GetPixelsAsync();

            CanvasRenderTarget rendertarget;

            using (var canvas = CanvasBitmap.CreateFromBytes(CanvasDevice.GetSharedDevice(), bfr,
                                                             rendertargetBitmap.PixelWidth, rendertargetBitmap.PixelHeight,
                                                             DirectXPixelFormat.B8G8R8A8UIntNormalized))
            {
                rendertarget = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), canvas.SizeInPixels.Width,
                                                      canvas.SizeInPixels.Height, 96);
                using (var ds = rendertarget.CreateDrawingSession())
                {
                    ds.DrawImage(canvas);
                }
            }

            return(MediaClip.CreateFromSurface(rendertarget, originalDuration));
        }
Exemplo n.º 33
0
        public void EnsureCurrentBufferMatchesWindow(CanvasRenderTarget[] accumulationBuffers, int currentBuffer)
        {
            if (UseCore)
            {
                var window = CoreWindow.GetForCurrentThread();
                var bound  = window.Bounds;
                RenderSize = new Size(bound.Width, bound.Height);
            }

            var buffer = accumulationBuffers[currentBuffer];

            if (buffer == null || !(SwapChainManager.SizeEqualsWithTolerance(buffer.Size, RenderSize)) || buffer.Dpi != DPI)
            {
                if (buffer != null)
                {
                    buffer.Dispose();
                }
                var wid = (float)RenderSize.Width;
                var hei = (float)RenderSize.Height;
                buffer = new CanvasRenderTarget(Device, wid, hei, DPI);
                accumulationBuffers[currentBuffer] = buffer;
            }
        }
Exemplo n.º 34
0
            public async Task <SoftwareBitmap> RenderAsync(IEnumerable <InkStroke> inkStrokes, double width, double height)
            {
                var dpi = DisplayInformation.GetForCurrentView().LogicalDpi;

                try
                {
                    var renderTarget = new CanvasRenderTarget(_canvasDevice, (float)width, (float)height, dpi); using (renderTarget)
                    {
                        using (var drawingSession = renderTarget.CreateDrawingSession())
                        {
                            drawingSession.DrawInk(inkStrokes);
                        }

                        return(await SoftwareBitmap.CreateCopyFromSurfaceAsync(renderTarget));
                    }
                }
                catch (Exception e) when(_canvasDevice.IsDeviceLost(e.HResult))
                {
                    _canvasDevice.RaiseDeviceLost();
                }

                return(null);
            }
Exemplo n.º 35
0
        private CanvasRenderTarget GetRenderTarget(Size scale, Rect signatureBounds, Size imageSize, float strokeWidth, Color strokeColor, Color backgroundColor)
        {
            var device    = CanvasDevice.GetSharedDevice();
            var offscreen = new CanvasRenderTarget(device, (int)imageSize.Width, (int)imageSize.Height, 96);

            using (var session = offscreen.CreateDrawingSession())
            {
                session.Clear(backgroundColor);

                session.Transform = Multiply(
                    CreateTranslation((float)-signatureBounds.X, (float)-signatureBounds.Y),
                    CreateScale((float)scale.Width, (float)scale.Height));

                foreach (var stroke in inkPresenter.GetStrokes())
                {
                    var points   = stroke.GetPoints();
                    var position = points.First();

                    var builder = new CanvasPathBuilder(device);
                    builder.BeginFigure((float)position.X, (float)position.Y);
                    foreach (var point in points)
                    {
                        builder.AddLine(new Vector2 {
                            X = (float)point.X, Y = (float)point.Y
                        });
                    }
                    builder.EndFigure(CanvasFigureLoop.Open);

                    var path  = CanvasGeometry.CreatePath(builder);
                    var color = strokeColor;
                    var width = (float)strokeWidth;
                    session.DrawGeometry(path, color, width);
                }
            }

            return(offscreen);
        }
        public static ImageInfo getIcon(String symbolID, int size, Color color, int outlineSize)
        {
            ImageInfo returnVal = null;
            if (_tgl == null)
                _tgl = TacticalGraphicLookup.getInstance();

            int mapping = _tgl.getCharCodeFromSymbol(symbolID);

            CanvasRenderTarget coreBMP = null;

            SVGPath svgTG = null;
            //SVGPath svgFrame = null;

            if (mapping > 0)
                svgTG = TGSVGTable.getInstance().getSVGPath(mapping);

            //float scale = 1;
            Matrix3x2 mScale, mTranslate;
            Matrix3x2 mIdentity = Matrix3x2.Identity;
            Rect rectF = new Rect();
            Matrix3x2 m = svgTG.CreateMatrix(size, size, out rectF, out mScale, out mTranslate);
            //svgTG.TransformToFitDimensions(size, size);
            Rect rr = svgTG.computeBounds(m);
            
            CanvasDevice device = CanvasDevice.GetSharedDevice();
            //CanvasRenderTarget offscreen = new CanvasRenderTarget(device, width, height, 96);
            coreBMP = new CanvasRenderTarget(device, (int)(rr.Width + 0.5), (int)(rr.Height + 0.5),96);

            using (CanvasDrawingSession cds = coreBMP.CreateDrawingSession())
            {
                svgTG.Draw(cds, Colors.Transparent, 0, color, m);
                cds.DrawRectangle(coreBMP.GetBounds(device), Colors.Red);
            }
            returnVal = new ImageInfo(coreBMP,new Point(coreBMP.Size.Width/2f,coreBMP.Size.Height/2.0f),new Rect(0,0,coreBMP.Size.Width,coreBMP.Size.Height),coreBMP.GetBounds(device));

            return returnVal;
        }
Exemplo n.º 37
0
        public static SoftwareBitmap CropAndResize(this SoftwareBitmap softwareBitmap, Rect bounds, float newWidth, float newHeight)
        {
            var resourceCreator = CanvasDevice.GetSharedDevice();

            using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
            {
                using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, newWidth, newHeight, canvasBitmap.Dpi))
                {
                    using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                    {
                        using (var scaleEffect = new ScaleEffect())
                        {
                            using (var cropEffect = new CropEffect())
                            {
                                using (var atlasEffect = new AtlasEffect())
                                {
                                    drawingSession.Clear(Colors.White);

                                    cropEffect.SourceRectangle = bounds;
                                    cropEffect.Source          = canvasBitmap;

                                    atlasEffect.SourceRectangle = bounds;
                                    atlasEffect.Source          = cropEffect;

                                    scaleEffect.Source = atlasEffect;
                                    scaleEffect.Scale  = new System.Numerics.Vector2(newWidth / (float)bounds.Width, newHeight / (float)bounds.Height);
                                    drawingSession.DrawImage(scaleEffect);
                                    drawingSession.Flush();

                                    return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied));
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 38
0
        public async Task <StorageFile> ExportFileWithImage(StorageFile imageFile, StorageFile saveFile)
        {
            if (saveFile == null)
            {
                return(null);
            }

            // Prevent updates to the file until updates are finalized with call to CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(saveFile);

            using (var outStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var device = CanvasDevice.GetSharedDevice();

                CanvasBitmap canvasbitmap;
                using (var stream = await imageFile.OpenAsync(FileAccessMode.Read))
                {
                    canvasbitmap = await CanvasBitmap.LoadAsync(device, stream);
                }

                using (var renderTarget = new CanvasRenderTarget(device, (int)_inkCanvas.Width, (int)_inkCanvas.Height, canvasbitmap.Dpi))
                {
                    using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession())
                    {
                        ds.DrawImage(canvasbitmap, new Rect(0, 0, (int)_inkCanvas.Width, (int)_inkCanvas.Height));
                        ds.DrawInk(_strokesService.GetStrokes());
                    }

                    await renderTarget.SaveAsync(outStream, CanvasBitmapFileFormat.Png);
                }
            }

            // Finalize write so other apps can update file.
            await CachedFileManager.CompleteUpdatesAsync(saveFile);

            return(saveFile);
        }
        private void CreateEffects()
        {
            _canvasRenderTarget = new CanvasRenderTarget(CanvasControl, (float)Window.Current.Bounds.Width,
                                                         (float)Window.Current.Bounds.Height, _canvasBitmap.Dpi);

            using (var ds = _canvasRenderTarget.CreateDrawingSession())
            {
                ds.DrawImage(_canvasBitmap, new Rect(new Point((Window.Current.Bounds.Width - _canvasBitmap.SizeInPixels.Width) / 2, 0), _canvasBitmap.Size));
            }

            var blur = new GaussianBlurEffect
            {
                BlurAmount = _blur,
                Source     = _canvasRenderTarget
            };

            var exposure = new ExposureEffect
            {
                Exposure = _exposure,
                Source   = blur
            };

            var saturation = new SaturationEffect
            {
                Saturation = _saturation,
                Source     = exposure
            };

            var contrast = new ContrastEffect
            {
                Contrast = _contrast,
                Source   = saturation
            };

            _effect = contrast;
            CanvasControl.Invalidate();
        }
Exemplo n.º 40
0
        public virtual CanvasBitmap GetImage(bool overlay, int layer)
        {
            CanvasDevice       device    = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget offscreen = new CanvasRenderTarget(device, 32, 32, 96);

            using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
            {
                if (lower != null)
                {
                    ds.DrawImage(lower.GetImage(false));
                }

                if (upper != null)
                {
                    if (lower.getType() == Block.Type.CLONEMACHINE)
                    {
                        ds.DrawImage(upper.GetImage(true));
                    }
                    else
                    {
                        ds.DrawImage(upper.GetImage(false));
                    }
                }

                if (visitorLow != null)
                {
                    ds.DrawImage(visitorLow.GetImage(true));
                }

                if (visitorHigh != null)
                {
                    ds.DrawImage(visitorHigh.GetImage(true));
                }
            }

            return(offscreen);
        }
Exemplo n.º 41
0
        public void Resize(ref ImageCanvasDataService imageHolst)
        {
            int width          = imageHolst.Width;
            int height         = imageHolst.Height;
            var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8,
                                                    imageHolst.Image.PixelWidth,
                                                    imageHolst.Image.PixelHeight);

            imageHolst.Image.CopyTo(softwareBitmap);
            byte[] imageBytes = new byte[softwareBitmap.PixelHeight * softwareBitmap.PixelWidth * 4];
            softwareBitmap.CopyToBuffer(imageBytes.AsBuffer());
            var resourceCreator = CanvasDevice.GetSharedDevice();
            var canvasBitmap    = CanvasBitmap.CreateFromBytes(
                resourceCreator,
                imageBytes,
                softwareBitmap.PixelWidth,
                softwareBitmap.PixelHeight,
                Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized,
                96.0f);

            var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, width, height, 96);

            using (var cds = canvasRenderTarget.CreateDrawingSession())
            {
                cds.DrawImage(canvasBitmap, canvasRenderTarget.Bounds);
            }

            var pixelBytes = canvasRenderTarget.GetPixelBytes();

            imageHolst.ImageSRC.DecodePixelHeight = height;
            imageHolst.ImageSRC.DecodePixelWidth  = width;

            var scaledSoftwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, width, height);

            scaledSoftwareBitmap.CopyFromBuffer(pixelBytes.AsBuffer());
            imageHolst.Image = scaledSoftwareBitmap;
        }
Exemplo n.º 42
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            using (CanvasBitmap input = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, context.InputFrame.Direct3DSurface))
                using (CanvasRenderTarget output = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, context.OutputFrame.Direct3DSurface))
                    using (CanvasDrawingSession ds = output.CreateDrawingSession())
                    {
                        TimeSpan time = context.InputFrame.RelativeTime.HasValue ? context.InputFrame.RelativeTime.Value : new TimeSpan();

                        float dispX = (float)Math.Cos(time.TotalSeconds) * 75f;
                        float dispY = (float)Math.Sin(time.TotalSeconds) * 75f;

                        ds.Clear(Colors.Black);

                        var dispMap = new DisplacementMapEffect()
                        {
                            Source         = input,
                            XChannelSelect = EffectChannelSelect.Red,
                            YChannelSelect = EffectChannelSelect.Green,
                            Amount         = 100f,
                            Displacement   = new Transform2DEffect()
                            {
                                TransformMatrix = Matrix3x2.CreateTranslation(dispX, dispY),
                                Source          = new BorderEffect()
                                {
                                    ExtendX = CanvasEdgeBehavior.Mirror,
                                    ExtendY = CanvasEdgeBehavior.Mirror,
                                    Source  = new TurbulenceEffect()
                                    {
                                        Octaves = 3
                                    }
                                }
                            }
                        };

                        ds.DrawImage(dispMap, -25f, -25f);
                    }
        }
Exemplo n.º 43
0
        /// <summary>
        /// Saves the entire bitmap to the specified stream
        /// with the specified file format and quality level.
        /// </summary>
        /// <param name="renderTarget"> The render target.</param>
        /// <param name="fileChoices"> The file choices. </param>
        /// <param name="suggestedFileName"> The suggested name of file. </param>
        /// <param name="fileFormat"> The file format. </param>
        /// <param name="quality"> The file quality. </param>
        /// <returns> Saved successful? </returns>
        public static async Task <bool> SaveCanvasBitmapFile(CanvasRenderTarget renderTarget, string fileChoices = ".Jpeg", string suggestedFileName = "Untitled", CanvasBitmapFileFormat fileFormat = CanvasBitmapFileFormat.Jpeg, float quality = 1.0f)
        {
            //FileSavePicker
            FileSavePicker savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.Desktop,
                SuggestedFileName      = suggestedFileName,
            };

            savePicker.FileTypeChoices.Add("DB", new[] { fileChoices });


            //PickSaveFileAsync
            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file == null)
            {
                return(false);
            }

            try
            {
                using (IRandomAccessStream accessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await renderTarget.SaveAsync(accessStream, fileFormat, quality);
                }

                renderTarget.Dispose();
                return(true);
            }
            catch (Exception)
            {
                renderTarget.Dispose();
                return(false);
            }
        }
Exemplo n.º 44
0
 private void CanvasSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
 {
     _canvas?.SwapChain?.ResizeBuffers((float)CanvasWidth, (float)CanvasHeight, 96);
     foreach (var layer in _layers)
     {
         var image = CanvasRenderTargetExtension.CreateEmpty(_canvas, new Size(CanvasWidth, CanvasHeight));
         using (var ds = image.CreateDrawingSession())
         {
             ds.DrawImage(layer.Image);
         }
         var old = layer.Image;
         layer.Image = image;
         old.Dispose();
     }
     if (_buffer == null)
     {
         return;
     }
     _buffer.Dispose();
     _tmpBuffer.Dispose();
     _buffer    = CanvasRenderTargetExtension.CreateEmpty(_canvas, new Size(CanvasWidth, CanvasHeight));
     _tmpBuffer = CanvasRenderTargetExtension.CreateEmpty(_canvas, new Size(CanvasWidth, CanvasHeight));
     Invalidate();
 }
        private void DrawCharData(CanvasDevice device, RenderingOptions options, HeartbeatMeasurement[] data)
        {
            //Size restrictions descriped in : http://microsoft.github.io/Win2D/html/P_Microsoft_Graphics_Canvas_CanvasDevice_MaximumBitmapSizeInPixels.htm
            float useHeight = (float)ChartWin2DCanvas.Size.Height > device.MaximumBitmapSizeInPixels ? device.MaximumBitmapSizeInPixels : (float)ChartWin2DCanvas.Size.Height;
            float useWidth  = data.Length > device.MaximumBitmapSizeInPixels ? device.MaximumBitmapSizeInPixels : data.Length;

            //this will change the values array to array with drawing-line-points for the graph
            List <DataPoint> dataList = FillOffsetList(data, options, useWidth, useHeight);

            //reset zoom & moving values
            _zoomFactor         = 100;
            _graphDrawingPoint  = new Point(0, 0);
            _graphDrawingSource = new Size(useWidth, useHeight);
            //create the graph image
            _offscreenChartImage = new CanvasRenderTarget(device, useWidth, useHeight, 96);

            using (CanvasDrawingSession ds = _offscreenChartImage.CreateDrawingSession())
            {
                //This creates drawing geometry from the drawing-line-points
                CanvasGeometry chart = getDrawChartGeometry(device, dataList);
                //and then we simply draw it with defined color
                ds.DrawGeometry(chart, 0, 0, GRAPG_COLOR);
            }
        }
Exemplo n.º 46
0
        public static SoftwareBitmap Crop(this SoftwareBitmap softwareBitmap, Rect bounds)
        {
            var resourceCreator = CanvasDevice.GetSharedDevice();

            using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
                using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, (float)bounds.Width, (float)bounds.Width, canvasBitmap.Dpi))
                    using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                        using (var cropEffect = new CropEffect())
                            using (var atlasEffect = new AtlasEffect())
                            {
                                drawingSession.Clear(Colors.White);

                                cropEffect.SourceRectangle = bounds;
                                cropEffect.Source          = canvasBitmap;

                                atlasEffect.SourceRectangle = bounds;
                                atlasEffect.Source          = cropEffect;

                                drawingSession.DrawImage(atlasEffect);
                                drawingSession.Flush();

                                return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)bounds.Width, (int)bounds.Width, BitmapAlphaMode.Premultiplied));
                            }
        }
Exemplo n.º 47
0
        public static void Blank()
        {
            App.Model.isCanUndo = false;//关闭撤销
            int index = App.Model.Index;

            //新建渲染目标=>层
            CanvasRenderTarget crt = new CanvasRenderTarget(App.Model.VirtualControl, App.Model.Width, App.Model.Height);
            Layer l = new Layer {
                Visual = true, Opacity = 100, CanvasRenderTarget = crt,
            };

            if (App.Model.isLowView)
            {
                l.LowView();
            }
            else
            {
                l.SquareView();
            }

            //Undo:撤销
            Undo undo = new Undo();

            undo.AddInstantiation(App.Model.Index);
            App.UndoAdd(undo);

            App.Model.Layers.Insert(App.Model.Index, l);
            l.SetWriteableBitmap(App.Model.VirtualControl);//刷新缩略图
            App.Model.Index = index + 1;

            App.Model.isReRender = true;                    //重新渲染
            App.Model.Refresh++;                            //画布刷新

            App.Model.LayersCount = App.Model.Layers.Count; //更新图层数量以供判断集合撤销
            App.Model.isCanUndo   = true;                   //打开撤销
        }
Exemplo n.º 48
0
        public static async Task <string> RenderImageWithInkToFileAsync(InkCanvas inker, IRandomAccessStream imageStream, string filename)
        {
            if (inker.InkPresenter.StrokeContainer.GetStrokes().Count == 0)
            {
                return(null);
            }

            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inker.ActualWidth, (int)inker.ActualHeight, 96);

            var image = await CanvasBitmap.LoadAsync(device, imageStream);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                var imageBounds = image.GetBounds(device);
                var min         = Math.Min(imageBounds.Height, imageBounds.Width);

                imageBounds.X      = (imageBounds.Width - min) / 2;
                imageBounds.Y      = (imageBounds.Height - min) / 2;
                imageBounds.Height = min;
                imageBounds.Width  = min;

                ds.Clear(Colors.White);
                ds.DrawImage(image, new Rect(0, 0, inker.ActualWidth, inker.ActualWidth), imageBounds);
                ds.DrawInk(inker.InkPresenter.StrokeContainer.GetStrokes());
            }

            var file = await(await AdventureObjectStorageHelper.GetDataSaveFolder()).CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg, 1f);
            }

            return(file.Path);
        }
        /// <summary>
        ///Render all layers with size.
        /// </summary>
        /// <param name="fileWidth"> The file width.</param>
        /// <param name="fileHeight"> The file height.</param>
        /// <param name="isClearWhite"> Clears to the white color. </param>
        /// <returns> The file image. </returns>
        public CanvasRenderTarget Render(int fileWidth = 256, int fileHeight = 256, bool isClearWhite = true)
        {
            ICanvasImage canvasImage = LayerBase.Render(LayerManager.CanvasDevice, LayerManager.RootLayerage);

            int canvasWidth  = this.CanvasTransformer.Width;
            int canvasHeight = this.CanvasTransformer.Height;

            CanvasRenderTarget renderTarget = new CanvasRenderTarget(LayerManager.CanvasDevice, fileWidth, fileHeight, 96);

            using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession())
            {
                if (isClearWhite)
                {
                    drawingSession.Clear(Colors.White);
                }

                if ((canvasImage is null) == false)
                {
                    float scaleX = fileWidth / canvasWidth;
                    float scaleY = fileHeight / canvasHeight;

                    Matrix3x2 matrix =
                        Matrix3x2.CreateTranslation(-canvasWidth / 2, -canvasHeight / 2) *
                        Matrix3x2.CreateScale(Math.Min(scaleX, scaleY)) *
                        Matrix3x2.CreateTranslation(fileWidth / 2, fileHeight / 2);

                    drawingSession.DrawImage(new Transform2DEffect
                    {
                        InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                        TransformMatrix   = matrix,
                        Source            = canvasImage
                    });
                }
            }
            return(renderTarget);
        }
Exemplo n.º 50
0
        public async Task <FileUpdateStatus> ExportInkToImageFile(PickerLocationId location, string fileName, Color backgroundColor)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };

            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();

            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);
                CanvasDevice device = CanvasDevice.GetSharedDevice();

                var localDpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
                CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)InkCanvas.ActualWidth, (int)InkCanvas.ActualHeight, localDpi);

                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(backgroundColor);
                    ds.DrawInk(InkCanvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);

                return(status);
            }
            return(FileUpdateStatus.Failed);
        }
Exemplo n.º 51
0
        private async void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            refreshImageSize();
            // grab output file
            StorageFolder storageFolder = KnownFolders.SavedPictures;
            var           file          = await storageFolder.CreateFileAsync("output.jpg", CreationCollisionOption.ReplaceExisting);

            CanvasDevice device = new CanvasDevice();

            device = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, imageWidth, imageHeight, 96);


            // grab your input file from Assets folder
            StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder assets             = await appInstalledFolder.GetFolderAsync("Assets");

            var inputFile = await assets.GetFileAsync("sample.jpg");

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.White);
                var image = await CanvasBitmap.LoadAsync(device, inputFile.Path);

                // draw your image first
                ds.DrawImage(image, new Rect(new Point(0, 0), new Point(imageWidth, imageHeight))); //Rect
                // then draw contents of your ink canvas over it
                ds.DrawInk(ink.InkPresenter.StrokeContainer.GetStrokes());
            }

            // save results
            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f);
            }
        }
        public static IRandomAccessStream GenerateFromString(string str, string fontFamily, Color color)
        {
            float size = 512;

            using (var device = new CanvasDevice())
                using (var renderTarget = new CanvasRenderTarget(device, size, size, 96))
                {
                    using (var ds = renderTarget.CreateDrawingSession())
                    {
                        ds.DrawText(str, size / 2, size / 2, color,
                                    new CanvasTextFormat()
                        {
                            FontFamily          = fontFamily,
                            FontSize            = size / 2,
                            HorizontalAlignment = CanvasHorizontalAlignment.Center,
                            VerticalAlignment   = CanvasVerticalAlignment.Center
                        });
                    }

                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png).AsTask().Wait();
                    return(stream);
                }
        }
Exemplo n.º 53
0
        private void DrawBackgroundBrush()
        {
            var dpi = GraphicsInformation.Dpi;

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

            using (var renderTarget = new CanvasRenderTarget(_device, 16, 16, dpi))
            {
                using (var drawingSession = renderTarget.CreateDrawingSession())
                {
                    drawingSession.Clear(Colors.Gray);
                    drawingSession.FillRectangle(8, 0, 8, 8, Colors.DarkGray);
                    drawingSession.FillRectangle(0, 8, 8, 8, Colors.DarkGray);
                }

                _backgroundBrush         = new CanvasImageBrush(_device, renderTarget);
                _backgroundBrush.ExtendX = CanvasEdgeBehavior.Wrap;
                _backgroundBrush.ExtendY = CanvasEdgeBehavior.Wrap;
            }
        }
Exemplo n.º 54
0
        public async Task <StorageFile> SaveInkImageToStorageFile(StorageFile file, Color backgroundColor)
        {
            CachedFileManager.DeferUpdates(file);

            CanvasDevice device = CanvasDevice.GetSharedDevice();

            var localDpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)InkCanvas.ActualWidth, (int)InkCanvas.ActualHeight, localDpi);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(backgroundColor);
                ds.DrawInk(InkCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
            }

            await CachedFileManager.CompleteUpdatesAsync(file);

            return(file);
        }
Exemplo n.º 55
0
        private async Task UpdateImageAsync()
        {
            var          iconImage = Element as IconImage;
            var          icon      = Plugin.Iconize.Iconize.FindIconForKey(iconImage.Icon);
            CanvasDevice device    = CanvasDevice.GetSharedDevice();
            var          target    = new CanvasRenderTarget(device, Convert.ToSingle(Element.HeightRequest), Convert.ToSingle(Element.HeightRequest), 96 * 4);

            using (var session = target.CreateDrawingSession())
                using (var format = new CanvasTextFormat {
                    FontSize = Convert.ToSingle(Element.HeightRequest), FontFamily = Plugin.Iconize.Iconize.FindModuleOf(icon).ToFontFamily().Source
                })
                    using (var textLayout = new CanvasTextLayout(device, $"{icon.Character}", format, Convert.ToSingle(Element.HeightRequest), Convert.ToSingle(Element.HeightRequest)))
                        session.DrawTextLayout(textLayout, 0, 0, iconImage.IconColor.ToWindowsColor());
            using (var stream = new InMemoryRandomAccessStream())
            {
                await target.SaveAsync(stream, CanvasBitmapFileFormat.Png);

                stream.Seek(0);
                BitmapImage result = new BitmapImage();
                await result.SetSourceAsync(stream);

                Control.Source = result;
            }
        }
Exemplo n.º 56
0
        private byte[] ConvertInkCanvasToByteArray(InkCanvas canvas)
        {
            var canvasStrokes = canvas.InkPresenter.StrokeContainer.GetStrokes();

            if (canvasStrokes.Count > 0)
            {
                var width        = (int)canvas.ActualWidth;
                var height       = (int)canvas.ActualHeight;
                var device       = CanvasDevice.GetSharedDevice();
                var renderTarget = new CanvasRenderTarget(device, width, height, 96);

                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(Windows.UI.Colors.White);
                    ds.DrawInk(canvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                return(renderTarget.GetPixelBytes());
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 57
0
        private async Task <StorageFile> ExportCanvasAsync()
        {
            var file = await GetImageToSaveAsync();

            if (file == null)
            {
                return(null);
            }

            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)_inkCanvas.Width, (int)_inkCanvas.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.DrawInk(_strokesService.GetStrokes());
            }

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png);
            }

            return(file);
        }
Exemplo n.º 58
0
        void DemandCreateBloomRenderTarget(ICanvasAnimatedControl sender)
        {
            // Early-out if we already have a rendertarget of the correct size.
            // Compare sizes as pixels rather than DIPs to avoid rounding artifacts.
            if (bloomRenderTarget != null &&
                bloomRenderTarget.SizeInPixels.Width == DipsToPixelSize(sender, (float)sender.Size.Width) &&
                bloomRenderTarget.SizeInPixels.Height == DipsToPixelSize(sender, (float)sender.Size.Height))
            {
                return;
            }

            // Destroy the old rendertarget.
            if (bloomRenderTarget != null)
            {
                bloomRenderTarget.Dispose();
            }

            // Create the new rendertarget.
            bloomRenderTarget = new CanvasRenderTarget(sender, sender.Size);

            // Configure the bloom effect to use this new rendertarget.
            extractBrightAreas.Source = bloomRenderTarget;
            bloomResult.Background    = bloomRenderTarget;
        }
Exemplo n.º 59
0
        void m_canvasControl_CreateResources(CanvasControl sender, object args)
        {
            m_bitmap_tiger      = null;
            m_bitmap_colorGrids = null;

            UpdateCanvasControlSize();
            m_imageBrush = new CanvasImageBrush(sender);

            m_offscreenTarget = new CanvasRenderTarget(sender, 100, 100);

            using (CanvasDrawingSession ds = m_offscreenTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.DarkBlue);
                ds.FillRoundedRectangle(new Rect(0, 0, 100, 100), 30, 30, Colors.DarkRed);
                ds.DrawRoundedRectangle(new Rect(0, 0, 100, 100), 30, 30, Colors.LightGreen);
                ds.DrawText("Abc", 0, 0, Colors.LightGray);
                ds.DrawText("Def", 25, 25, Colors.LightGray);
                ds.DrawText("Efg", 50, 50, Colors.LightGray);
            }

            CanvasGradientStop[] stops = new CanvasGradientStop[4];
            stops[0].Position     = 0;
            stops[0].Color        = Colors.Black;
            stops[1].Position     = 1;
            stops[1].Color        = Colors.White;
            stops[2].Position     = 0.2f;
            stops[2].Color        = Colors.Purple;
            stops[3].Position     = 0.7f;
            stops[3].Color        = Colors.Green;
            m_linearGradientBrush = CanvasLinearGradientBrush.CreateRainbow(sender, 0.0f);
            m_radialGradientBrush = new CanvasRadialGradientBrush(
                sender,
                stops,
                CanvasEdgeBehavior.Clamp,
                CanvasAlphaMode.Premultiplied);
        }
Exemplo n.º 60
0
        public void updateRepresentation()
        {
            //UpdateWidth();
            try
            {
                if (boundBox.Height > 0 && boundBox.Width > 0)
                {
                    CanvasDevice device = CanvasDevice.GetSharedDevice();

                    represent = new CanvasRenderTarget(device, (int)this.boundBox.Width, (int)this.boundBox.Height, 96);

                    using (CanvasDrawingSession g2d = represent.CreateDrawingSession())
                    {
                        g2d.Clear(Colors.Transparent);

                        g2d.Antialiasing = CanvasAntialiasing.Antialiased;

                        //int linesize = 5;

                        Color fillbrush = NodeColor;

                        if (hovered)
                        {
                            fillbrush = Colors.Black;
                        }

                        style.DrawStyle(g2d, NodeDrawingStyle, 0, 0, (int)boundBox.Width - 2, (int)boundBox.Height - 2, fillbrush, BorderColor, (int)(borderOffset * scale));

                        g2d.DrawText(text, 0, 0, TextColor, NodeTextStyle);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }