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; } }
public win2d_Button(CanvasDevice device, Vector2 position, int width, int height, string text) : base(position, width, height) { Color = Colors.Gray; TextLayout = new CanvasTextLayout(device, text, Statics.DefaultFontNoWrap, 0, 0); RecalculateLayout(); }
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(); } }
public void Run(IBackgroundTaskInstance taskInstance) { using (device = new CanvasDevice()) { try { GenerateTileImage(TileTemplateType.TileSquare150x150Image, 150, 150); GenerateTileImage(TileTemplateType.TileWide310x150Image, 310, 150); } catch (Exception e) { if (device.IsDeviceLost(e.HResult)) { // When the device is lost we don't attempt to retry, and instead just wait for // the next time the task runs. return; } // Any other errors we bubble up throw; } } UpdateLiveTiles(); DeleteOldLiveTileImageFiles(); LiveTileUpdater.SetLatestTileImagesInSettings(tiles.Values); }
public static World Create(CanvasDevice device, int widthInTiles, int heightInTiles, IProgress<Tuple<string, float>> progress) { World world = new World(); ProtoWorld pw = new ProtoWorld(device, widthInTiles, heightInTiles, progress); while (pw.Aborted) { pw = new ProtoWorld(device, widthInTiles, heightInTiles, progress); } world.Width = pw.Width; world.Height = pw.Height; foreach (ProtoRegion pr in pw.ProtoRegions) { world.Regions.Add(Region.FromProtoRegion(pr)); } foreach (ProtoRegion pcr in pw.ProtoCaves) { world.Caves.Add(Region.FromProtoRegion(pcr)); } world.RenderTargetRegions = pw.RenderTargetRegions; world.RenderTargetSubregions = pw.RenderTargetSubregions; world.RenderTargetPaths = pw.RenderTargetPaths; world.RenderTargetHeightMap = pw.RenderTargetHeightMap; world.RenderTargetCaves = pw.RenderTargetCaves; world.RenderTargetCavePaths = pw.RenderTargetCavePaths; return world; }
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); }
public void Append(CanvasDevice device, string str) { lock (Strings) { Strings.Add(device, str); } }
public win2d_TextboxCursor(CanvasDevice device, Color color) { Color = color; LastUpdate = TimeSpan.Zero; CursorCharacter = new CanvasTextLayout(device, "|", Statics.DefaultFontNoWrap, 0, 0); }
public win2d_TextblockStringCollection(CanvasDevice device, Vector2 position, int drawingwidth, int drawingheight, bool scrolltobottomonappend = false) { _device = device; Position = position; DrawingWidth = drawingwidth; DrawingHeight = drawingheight; ScrollToBottomOnAppend = scrolltobottomonappend; }
public ParticlesManager(CanvasAnimatedControl canvas, int amount = 10) { parent = canvas; device = canvas.Device; bounds = new Size(canvas.ActualWidth, canvas.ActualHeight); clearColor = (canvas.Background as SolidColorBrush).Color; amountparticles = amount; }
private void CreateResources(Size sizeSwapchain) { _device = new CanvasDevice(); _swapchain = new CanvasSwapChain(_device, (float)sizeSwapchain.Width, (float)sizeSwapchain.Height, 96); // Start rendering the swapchain StartRendering(sizeSwapchain); }
public void CreateFromBuffer() { var device = new CanvasDevice(); byte[] somePixelData = { 1, 2, 3, 4 }; var buffer = somePixelData.AsBuffer(); // Overload #1 var bitmap = CanvasBitmap.CreateFromBytes(device, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized); Assert.AreEqual(2u, bitmap.SizeInPixels.Width); Assert.AreEqual(2u, bitmap.SizeInPixels.Height); Assert.AreEqual(96, bitmap.Dpi); Assert.AreEqual(DirectXPixelFormat.A8UIntNormalized, bitmap.Format); Assert.AreEqual(CanvasAlphaMode.Premultiplied, bitmap.AlphaMode); CollectionAssert.AreEqual(somePixelData, bitmap.GetPixelBytes()); // Overload #2 const float someDpi = 123.0f; bitmap = CanvasBitmap.CreateFromBytes(device, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi); Assert.AreEqual(2u, bitmap.SizeInPixels.Width); Assert.AreEqual(2u, bitmap.SizeInPixels.Height); Assert.AreEqual(someDpi, bitmap.Dpi); Assert.AreEqual(DirectXPixelFormat.A8UIntNormalized, bitmap.Format); Assert.AreEqual(CanvasAlphaMode.Premultiplied, bitmap.AlphaMode); CollectionAssert.AreEqual(somePixelData, bitmap.GetPixelBytes()); // Overload #3 bitmap = CanvasBitmap.CreateFromBytes(device, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi, CanvasAlphaMode.Straight); Assert.AreEqual(2u, bitmap.SizeInPixels.Width); Assert.AreEqual(2u, bitmap.SizeInPixels.Height); Assert.AreEqual(someDpi, bitmap.Dpi); Assert.AreEqual(DirectXPixelFormat.A8UIntNormalized, bitmap.Format); Assert.AreEqual(CanvasAlphaMode.Straight, bitmap.AlphaMode); CollectionAssert.AreEqual(somePixelData, bitmap.GetPixelBytes()); // Null device. Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(null, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized)); Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(null, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi)); Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(null, buffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi, CanvasAlphaMode.Straight)); // Null buffer. IBuffer nullBuffer = null; Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(device, nullBuffer, 2, 2, DirectXPixelFormat.A8UIntNormalized)); Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(device, nullBuffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi)); Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(device, nullBuffer, 2, 2, DirectXPixelFormat.A8UIntNormalized, someDpi, CanvasAlphaMode.Straight)); // Too small a buffer. Assert.ThrowsException<ArgumentException>(() => CanvasBitmap.CreateFromBytes(device, buffer, 3, 3, DirectXPixelFormat.A8UIntNormalized)); }
public FeedItemLayoutData(CanvasDevice device, FeedItem feedItem, float fRequestedWidth) { FeedDataTitleLayout = new CanvasTextLayout(device, feedItem.FeedDataTitle, Statics.DefaultFont, fRequestedWidth, 20); PublicationDateLayout = new CanvasTextLayout(device, feedItem.PublicationDate.ToString("MM/dd/yy"), Statics.DefaultFont, fRequestedWidth, 20); // MMMM dd, yyyy - h:mm TitleLayout = new CanvasTextLayout(device, feedItem.Title, Statics.DefaultFont, fRequestedWidth, 20); AuthorLayout = new CanvasTextLayout(device, feedItem.Author, Statics.DefaultFont, fRequestedWidth, 20); if (feedItem.Title != feedItem.Content) { ContentLayout = new CanvasTextLayout(device, feedItem.Content, Statics.DefaultFont, fRequestedWidth, 20); } LinkLayout = new CanvasTextLayout(device, feedItem.Link.ToString(), Statics.DefaultFont, fRequestedWidth, 20); }
public win2d_Textblock(CanvasDevice device, Vector2 position, int width, int height, bool scrolltobottomonappend = false) : base(position, width, height) { _device = device; Strings = new win2d_TextblockStringCollection(_device, new Vector2(Position.X + PaddingX, Position.Y + PaddingY), Width - PaddingY * 2, Height - PaddingY * 2, scrolltobottomonappend); }
public static void Initialize(CanvasDevice device) { LoadCharacterWidths(device); UpArrow = new CanvasTextLayout(device, "\u2191", Statics.DefaultFontNoWrap, 0, 0); DoubleUpArrow = new CanvasTextLayout(device, "\u219f", Statics.DefaultFontNoWrap, 0, 0); DownArrow = new CanvasTextLayout(device, "\u2193", Statics.DefaultFontNoWrap, 0, 0); DoubleDownArrow = new CanvasTextLayout(device, "\u21a1", Statics.DefaultFontNoWrap, 0, 0); }
public win2d_Button(CanvasDevice device, Vector2 position, int width, int height, string text) : base(position, width, height) { ButtonRectangle = new Rect(Position.X, Position.Y, Width, Height); TextLayout = new CanvasTextLayout(device, text, Statics.DefaultFontNoWrap, 0, 0); TextLayoutPosition = new Vector2(Position.X + (Width - (float)TextLayout.LayoutBounds.Width) / 2, Position.Y + (Height - (float)TextLayout.LayoutBounds.Height) / 2); Color = Colors.Gray; }
/// <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); }
static public void Initialize(Compositor compositor) { Debug.Assert(!_intialized); _compositor = compositor; _canvasDevice = new CanvasDevice(); _compositionDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice); _intialized = true; }
public void TestBitmapPixelFormats() { var device = new CanvasDevice(); foreach (var format in AllPixelFormats()) { // Unknown formats should not be supported. if (!formatFlags.ContainsKey(format)) { Assert.IsFalse(device.IsPixelFormatSupported(format)); ValidateCannotCreateBitmap(device, format, FirstSupportedAlphaMode(format)); continue; } // Optional formats may be legitimately not supported, depending on the device. if (!device.IsPixelFormatSupported(format)) { Assert.IsTrue((formatFlags[format] & FormatFlags.Optional) != 0); ValidateCannotCreateBitmap(device, format, FirstSupportedAlphaMode(format)); continue; } // We should be able to create this format using all its supported alpha modes. var lotsOfZeroes = new byte[1024]; foreach (var alphaMode in SupportedAlphaModes(format)) { CanvasBitmap.CreateFromBytes(device, lotsOfZeroes, 4, 4, format, 96, alphaMode); } // Other alpha modes should not be supported. foreach (var alphaMode in UnsupportedAlphaModes(format)) { ValidateCannotCreateBitmap(device, format, alphaMode); } // We should also be able to create this format without explicitly specifying an alpha mode. var bitmap = CanvasBitmap.CreateFromBytes(device, lotsOfZeroes, 4, 4, format); Assert.AreEqual(FirstSupportedAlphaMode(format), bitmap.AlphaMode); // Some formats can be drawn directly, while others cannot. if ((formatFlags[format] & FormatFlags.CannotDraw) == 0) { ValidateCanDrawImage(device, bitmap); } else { ValidateCannotDrawImage(device, bitmap); } // But all formats should be drawable when used as effect inputs. ValidateCanDrawImage(device, new ColorMatrixEffect { Source = bitmap }); } }
/// <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 Render(String symbolID, Dictionary<int, String> modifiers, Dictionary<int, String> attributes, CanvasDevice device) { SinglePointRenderer spr = SinglePointRenderer.getInstance(); int symStd = 1; if (modifiers != null && modifiers[MilStdAttributes.SymbologyStandard] != null) { symStd = Convert.ToInt32(modifiers[MilStdAttributes.SymbologyStandard]); } else { if (modifiers == null) modifiers = new Dictionary<int, String>(); modifiers[MilStdAttributes.SymbologyStandard] = Convert.ToString(RendererSettings.getInstance().getSymbologyStandard()); } var basicID = SymbolUtilities.getBasicSymbolIDStrict(symbolID); if (SymbolUtilities.isTacticalGraphic(symbolID)) { SymbolDef sd = SymbolDefTable.getInstance().getSymbolDef(basicID, symStd); if (sd == null) { sd = SymbolDefTable.getInstance().getSymbolDef(basicID, symStd); } if (sd != null && sd.getDrawCategory() == SymbolDef.DRAW_CATEGORY_POINT) { return spr.RenderSPTG(symbolID, modifiers, attributes); } else { Color color = SymbolUtilities.getLineColorOfAffiliation(symbolID); int size = 35; if (modifiers.ContainsKey(MilStdAttributes.LineColor)) color = SymbolUtilities.getColorFromHexString(modifiers[MilStdAttributes.LineColor]); if (modifiers.ContainsKey(MilStdAttributes.PixelSize)) size = int.Parse(modifiers[MilStdAttributes.PixelSize]); return TacticalGraphicIconRenderer.getIcon(symbolID,size, color,0); } } else if (UnitFontLookup.getInstance().getLookupInfo(basicID) != null) { return spr.RenderUnit(symbolID, modifiers, attributes, device); } else { //symbolID = SymbolUtilities.reconcileSymbolID(symbolID, false); return spr.RenderUnit(symbolID, modifiers, attributes, null); } }
public void Add(CanvasDevice device, string str) { win2d_TextblockString s = new win2d_TextblockString(device, str, DrawingWidth); Strings.Add(s); _totalstringsheight += s.Height + StringPaddingY; if(ScrollToBottomOnAppend) { ScrollToBottom(); } }
public static void Initialize(CanvasDevice device) { _device = device; // set panel dimensions Vector2 CustomizationPanelPosition = new Vector2(Statics.CanvasWidth - 400, Statics.Padding); int CustomizationPanelWidth = 400 - Statics.Padding; int CustomizationPanelHeight = Statics.CanvasHeight - Statics.Padding * 2; CustomizationPanel = new win2d_Panel(CustomizationPanelPosition, CustomizationPanelWidth, CustomizationPanelHeight, Colors.Black); AddControls(); }
public win2d_Slider(CanvasDevice device, Vector2 position, int width, string text, int minValue, int maxValue, int startingValue) : base(position, width, -1) { _device = device; _minValue = minValue; _maxValue = maxValue; _textlayout = new CanvasTextLayout(_device, text, Statics.DefaultFontNoWrap, 0, 0); _sliderbarrect = new Rect(Position.X, Position.Y + _textlayout.LayoutBounds.Height + Statics.Padding, Width, 10); Height = (int)_textlayout.LayoutBounds.Height + Statics.Padding + 10; }
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); }
public win2d_Textbox(CanvasDevice device, Vector2 position, int width) : base(position, width, -1) { _device = device; CanvasTextLayout layout = new CanvasTextLayout(_device, "TEST!", Statics.DefaultFontNoWrap, 0, 0); Height = (int)layout.LayoutBounds.Height + PaddingY * 2; Color = Colors.White; Cursor = new win2d_TextboxCursor(_device, Colors.White); CursorStringIndex = 0; RecalculateLayout(); }
public void SetDevice(CanvasDevice device, Size windowSize) { ++deviceCount; drawLoopCancellationTokenSource?.Cancel(); swapChain = new CanvasSwapChain(device, 256, 256, 96); swapChainVisual.Brush = compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(compositor, swapChain)); drawLoopCancellationTokenSource = new CancellationTokenSource(); Task.Factory.StartNew( DrawLoop, drawLoopCancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
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; }
public async Task Load(CanvasDevice device, StorageFile file) { using (var stream = await file.OpenReadAsync()) { SourceBitmap = await CanvasBitmap.LoadAsync(device, stream); } bitmapFormat = sourceBitmap.Format; bitmapData = sourceBitmap.GetPixelBytes(); Size = sourceBitmap.Size.ToVector2(); Edits.Clear(); Edits.Add(new EditGroup(this)); SelectedEffect = null; }
public static void SetProgress(CanvasDevice device, Tuple<string, float> progress) { ProgressPhaseTextLayout = new CanvasTextLayout(device, progress.Item1, Statics.FontMedium, 0, 0); float x = (float)(Statics.CanvasWidth - ProgressPhaseTextLayout.LayoutBounds.Width) / 2; float y = (float)(Statics.CanvasHeight - ProgressPhaseTextLayout.LayoutBounds.Height) / 2; ProgressPhaseTextLayoutPosition = new Vector2(x, y); ProgressPercentage = progress.Item2; ProgressPercentageRect = new Rect((Statics.CanvasWidth - ProgressBarWidth) / 2, ProgressPhaseTextLayoutPosition.Y + ProgressPhaseTextLayout.LayoutBounds.Height + 10, ProgressBarWidth * ProgressPercentage, 20); ProgressPercentageBorderRect = new Rect((Statics.CanvasWidth - ProgressBarWidth) / 2, ProgressPhaseTextLayoutPosition.Y + ProgressPhaseTextLayout.LayoutBounds.Height + 10, ProgressBarWidth, 20); }
private async void SaveButton_Click(object sender, RoutedEventArgs e) { // Here we have to create a CanvasRenderTarget and then draw // our content there. Then we can save that as an image. This // is why we abstracted the draw away from our CanvasControl's // event handler. // Get our storage file var file = await GetTargetFileAsync(); // If the user cancels or does not wish to save the image, then // our file object should be null. Don't continue if that's the // case. if (file == null) { return; } // Get the CanvasDevice (You can think of this like a Direct3D device) var canvasDevice = CanvasDevice.GetSharedDevice(); // Create our render target using (var renderTarget = new CanvasRenderTarget(canvasDevice, // Device 200, // Width 200, // Height 96)) // DPI (this doesn't matter // as much sicne we aren't // displaying this to the // screen and are instead // saving directly to an image) { // Draw to our render target using (var drawingSession = renderTarget.CreateDrawingSession()) { Draw(drawingSession); } // Save to an image using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png); } } }
public async Task <Size> DrawOutlineTextWithLibrary(int dim, string font, string text, string saved_file) { Size size = new Size(); CanvasDevice device = CanvasDevice.GetSharedDevice(); using (CanvasRenderTarget offscreen = new CanvasRenderTarget(device, dim, dim, 96, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized, CanvasAlphaMode.Premultiplied)) { using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Colors.White); } Color text_color = Colors.White; CanvasSolidColorBrush brush = new CanvasSolidColorBrush(device, text_color); CanvasTextFormat format = new CanvasTextFormat(); format.FontFamily = font; format.FontStyle = Windows.UI.Text.FontStyle.Normal; format.FontSize = 60; format.FontWeight = Windows.UI.Text.FontWeights.Bold; float layoutWidth = dim; float layoutHeight = dim; CanvasTextLayout textLayout = new CanvasTextLayout(device, text, format, layoutWidth, layoutHeight); ITextStrategy strat = CanvasHelper.TextOutline(Colors.Blue, Colors.Black, 10); CanvasHelper.DrawTextImage(strat, offscreen, new Point(10.0, 10.0), textLayout); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder; string saved_file2 = "\\"; saved_file2 += saved_file; await offscreen.SaveAsync(storageFolder.Path + saved_file2); imgOutlineText.Source = new BitmapImage(new Uri(storageFolder.Path + saved_file2)); using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Colors.White); } return(size); } }
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 segments = stroke.GetRenderingSegments(); var position = segments.First().Position; var builder = new CanvasPathBuilder(device); builder.BeginFigure((float)position.X, (float)position.Y); foreach (var segment in segments.Skip(1)) { builder.AddCubicBezier( new Vector2 { X = (float)segment.BezierControlPoint1.X, Y = (float)segment.BezierControlPoint1.Y }, new Vector2 { X = (float)segment.BezierControlPoint2.X, Y = (float)segment.BezierControlPoint2.Y }, new Vector2 { X = (float)segment.Position.X, Y = (float)segment.Position.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); }
public void SetDevice(CanvasDevice device) { drawLoopCancellationTokenSource?.Cancel(); var displayInfo = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); this.swapChain = new CanvasSwapChain( device, (int)this.ActualWidth, (int)this.ActualHeight, displayInfo.LogicalDpi, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, CanvasAlphaMode.Premultiplied); swapChainVisual.Brush = Window.Current.Compositor.CreateSurfaceBrush(CanvasComposition.CreateCompositionSurfaceForSwapChain(Window.Current.Compositor, swapChain)); drawLoopCancellationTokenSource = new CancellationTokenSource(); }
void CreateDevice() { device = CanvasDevice.GetSharedDevice(); device.DeviceLost += Device_DeviceLost; if (compositionGraphicsDevice == null) { compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, device); } else { CanvasComposition.SetCanvasDevice(compositionGraphicsDevice, device); } if (swapChainRenderer != null) { swapChainRenderer.SetDevice(device, new Size(window.Bounds.Width, window.Bounds.Height)); } }
public Task <Microsoft.UI.Xaml.Media.ImageSource> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken)) { if (!(imagesource is FontImageSource fontsource)) { return(null); } var device = CanvasDevice.GetSharedDevice(); // https://github.com/microsoft/microsoft-ui-xaml/issues/4205#issuecomment-780204896 // var dpi = Math.Max(_minimumDpi, Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi); var dpi = _minimumDpi; var textFormat = new CanvasTextFormat { FontFamily = GetFontSource(fontsource), FontSize = (float)fontsource.Size, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center, Options = CanvasDrawTextOptions.Default }; using (var layout = new CanvasTextLayout(device, fontsource.Glyph, textFormat, (float)fontsource.Size, (float)fontsource.Size)) { var canvasWidth = (float)layout.LayoutBounds.Width + 2; var canvasHeight = (float)layout.LayoutBounds.Height + 2; var imageSource = new CanvasImageSource(device, canvasWidth, canvasHeight, dpi); using (var ds = imageSource.CreateDrawingSession(Microsoft.UI.Colors.Transparent)) { var iconcolor = (fontsource.Color != null ? fontsource.Color : Colors.White).ToWindowsColor(); // offset by 1 as we added a 1 inset var x = (float)layout.DrawBounds.X * -1; ds.DrawTextLayout(layout, x, 1f, iconcolor); } return(Task.FromResult((UI.Xaml.Media.ImageSource)imageSource)); } }
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); } }
public unsafe void UpdateFromCoreOutputXRGB8888(CanvasDevice device, IReadOnlyList <uint> data, uint width, uint height, ulong pitch) { if (data == null || RenderTarget == null || CurrentCorePixelSize == 0) { return; } lock (RenderTargetLock) { RenderTargetViewport.Width = width; RenderTargetViewport.Height = height; using (var renderTargetMap = new D3DSurfaceMap(device, RenderTargetSurface)) { var dataPtr = (byte *)new IntPtr(renderTargetMap.Data).ToPointer(); FramebufferConverter.ConvertFrameBufferXRGB8888(width, height, data, (int)pitch, dataPtr, (int)renderTargetMap.PitchBytes); } } }
private async void mediaPlayer_VideoFrameAvailable_Subtitle(MediaPlayer sender, object args) { CanvasDevice canvasDevice = CanvasDevice.GetSharedDevice(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (frameServerDest == null) { // FrameServerImage in this example is a XAML image control frameServerDest = new SoftwareBitmap(BitmapPixelFormat.Rgba8, (int)FrameServerImage.Width, (int)FrameServerImage.Height, BitmapAlphaMode.Ignore); } if (canvasImageSource == null) { canvasImageSource = new CanvasImageSource(canvasDevice, (int)FrameServerImage.Width, (int)FrameServerImage.Height, DisplayInformation.GetForCurrentView().LogicalDpi);//96); FrameServerImage.Source = canvasImageSource; } using (CanvasBitmap inputBitmap = CanvasBitmap.CreateFromSoftwareBitmap(canvasDevice, frameServerDest)) { using (CanvasDrawingSession ds = canvasImageSource.CreateDrawingSession(Windows.UI.Colors.Black)) { mediaPlayer.CopyFrameToVideoSurface(inputBitmap); //Rect subtitleTargetRect = new Rect(0, 0, inputBitmap.Bounds.Width, inputBitmap.Bounds.Bottom * .1); Rect subtitleTargetRect = new Rect(0, 0, 100, 100); mediaPlayer.RenderSubtitlesToSurface(inputBitmap);//, subtitleTargetRect); //var gaussianBlurEffect = new GaussianBlurEffect //{ // Source = inputBitmap, // BlurAmount = 5f, // Optimization = EffectOptimization.Speed //}; //ds.DrawImage(gaussianBlurEffect); ds.DrawImage(inputBitmap); } } }); }
public void SetEncodingProperties(VideoEncodingProperties encodingProperties, IDirect3DDevice device) { canvasDevice = CanvasDevice.CreateFromDirect3D11Device(device, CanvasDebugLevel.None); numColumns = (uint)(encodingProperties.Width / pixelsPerTile); numRows = (uint)(encodingProperties.Height / pixelsPerTile); transforms = new Transform2DEffect[numColumns, numRows]; crops = new CropEffect[numColumns, numRows]; for (uint i = 0; i < numColumns; i++) { for (uint j = 0; j < numRows; j++) { crops[i, j] = new CropEffect(); crops[i, j].SourceRectangle = new Rect(i * pixelsPerTile, j * pixelsPerTile, pixelsPerTile, pixelsPerTile); transforms[i, j] = new Transform2DEffect(); transforms[i, j].Source = crops[i, j]; } } }
private static async Task <CompositionDrawingSurface> GetCompositionDrawingSurface(Compositor compositor, RenderTargetBitmap renderTargetBitmap) { using (var canvasDevice = new CanvasDevice()) using (CompositionGraphicsDevice graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice)) using (CanvasBitmap canvasBitmap = await GetCanvasBitmap(renderTargetBitmap, canvasDevice)) { CompositionDrawingSurface surface = graphicsDevice.CreateDrawingSurface( new Size(canvasBitmap.Size.Width, canvasBitmap.Size.Height), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Ignore); using (CanvasDrawingSession session = CanvasComposition.CreateDrawingSession(surface)) { session.Clear(Color.FromArgb(0, 0, 0, 0)); session.DrawImage(canvasBitmap, new Rect(0, 0, surface.Size.Width, surface.Size.Height), new Rect(0, 0, canvasBitmap.Size.Width, canvasBitmap.Size.Height)); } return(surface); } }
static async Task <string> GenerateAndSaveTileImage(CanvasDevice device, float width, float height) { using (var renderTarget = new CanvasRenderTarget(device, width, height, 96)) { using (var ds = renderTarget.CreateDrawingSession()) { DrawTile(ds, width, height); } var filename = string.Format("tile-{0}x{1}-{2}.png", (int)width, (int)height, Guid.NewGuid().ToString()); await renderTarget.SaveAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, filename)); return(filename); } }
public async Task <int> InitializeCam() { if (gcitem == null) { return(1); } if (canvasDevice == null) { canvasDevice = new CanvasDevice(); } if (framePool == null) { /* * //only 2 frames ... depending on the number of buffers * framePool = Direct3D11CaptureFramePool.Create( * canvasDevice, // D3D device * DirectXPixelFormat.B8G8R8A8UIntNormalized, // Pixel format * 2, // Number of frames * gcitem.Size); // Size of the buffers */ framePool = Direct3D11CaptureFramePool.CreateFreeThreaded( canvasDevice, DirectXPixelFormat.B8G8R8A8UIntNormalized, 1, gcitem.Size); } initialRecordTime = DateTime.Now; previousRecordTime = DateTime.Now; currentFrame = null; unpackList = new List <UnpackItem>(); _currentVideoStreamPos = 0; tempFile = null; return(0); }
internal ImageAssetManager(string imagesFolder, IImageAssetDelegate @delegate, Dictionary <string, LottieImageAsset> imageAssets, CanvasDevice context) { _imagesFolder = imagesFolder; _context = context; if (!string.IsNullOrEmpty(imagesFolder) && _imagesFolder[_imagesFolder.Length - 1] != '/') { _imagesFolder += '/'; } //if (!(callback is UIElement)) // TODO: Makes sense on UWP? //{ // Debug.WriteLine("LottieDrawable must be inside of a view for images to work.", L.TAG); // this.imageAssets = new Dictionary<string, LottieImageAsset>(); // return; //} _imageAssets = imageAssets; Delegate = @delegate; }
void CreateDevice() { Device = CanvasDevice.GetSharedDevice(); Device.DeviceLost += Device_DeviceLost; if (CompositionGraphicsDevice == null) { CompositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(Compositor, Device); } else { CanvasComposition.SetCanvasDevice(CompositionGraphicsDevice, Device); } if (SwapChainRenderer != null) { SwapChainRenderer.SetDevice(Device, new Size(Window.Bounds.Width, Window.Bounds.Height)); } }
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); } }
protected ICompositionSurface CreateSurface() { double width = 20; double height = 20; CanvasDevice device = CanvasDevice.GetSharedDevice(); var graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, device); CompositionSurfaceBrush drawingBrush = _compositor.CreateSurfaceBrush(); var drawingSurface = graphicsDevice.CreateDrawingSurface( new Size(width, height), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); /* Create Drawing Session is not thread safe - only one can ever be active per app */ using (var ds = CanvasComposition.CreateDrawingSession(drawingSurface)) { ds.Clear(Colors.Transparent); ds.DrawCircle(new Vector2(10, 10), 5, Colors.Black, 3); } }
private async Task <bool> Save_InkedImagetoStream(IRandomAccessStream stream) { bool hasXamlOverlay = xamloverlay.Children.Count > 0; if (_data == null) { _data = Player.InkNoteData; } if (_data == null) { return(false); } using (var imageStream = await _data.GetImageStream()) { CanvasDevice device = CanvasDevice.GetSharedDevice(); var image = await CanvasBitmap.LoadAsync(device, imageStream); using (var renderTarget = new CanvasRenderTarget(device, (int)inkingCanvas.ActualWidth, (int)inkingCanvas.ActualHeight, 96)) { using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession()) { ds.Clear(Colors.White); ds.DrawImage(image, new Rect(0, 0, (int)inkingCanvas.ActualWidth, (int)inkingCanvas.ActualHeight)); if (hasXamlOverlay) { await DrawXamlOverlay(device, renderTarget, ds); } ds.Units = CanvasUnits.Pixels; ds.DrawInk(inkingCanvas.InkPresenter.StrokeContainer.GetStrokes()); } await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png); } } return(true); }
private void OnCopy() { if (_clipboardBorder == null) { return; } var device = CanvasDevice.GetSharedDevice(); var border = _clipboardBorder.ToRect(); var drawings = CanvasBitmap.CreateFromBytes(device, GetDrawings().GetPixelBytes(), (int)(_bitmap.Size.Width * _scale), (int)(_bitmap.Size.Height * _scale), _bitmap.Format); var clipboardBytes = drawings.GetPixelBytes((int)(border.X), (int)(border.Y), (int)(border.Width), (int)(border.Height)); _clipboard = CanvasBitmap.CreateFromBytes(device, clipboardBytes, (int)(border.Width), (int)(border.Height), drawings.Format, drawings.Dpi, drawings.AlphaMode); }
private CanvasRenderTarget CreateOpacityMask(ICanvasResourceCreator resourceCreator, double width, double height) { var device = CanvasDevice.GetSharedDevice(); var target = new CanvasRenderTarget(device, (float)width, (float)height, 96); using (var session = target.CreateDrawingSession()) { session.Clear(Colors.Transparent); _maskGeometry.Add(ResourcesFactory.CreateCloud(session)); _maskGeometry.Add(ResourcesFactory.CreateCircle(session)); foreach (var geometry in _maskGeometry) { session.FillGeometry(geometry, Colors.White); } } return(target); }
public static SoftwareBitmap Resize(this SoftwareBitmap softwareBitmap, 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()) { drawingSession.Clear(Colors.White); scaleEffect.Source = canvasBitmap; scaleEffect.Scale = new System.Numerics.Vector2(newWidth / canvasBitmap.SizeInPixels.Width, newHeight / canvasBitmap.SizeInPixels.Height); drawingSession.DrawImage(scaleEffect); drawingSession.Flush(); return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied)); } }
public void PixelShaderEffect_Realize_NoConstants() { const string hlsl = @" float4 main() : SV_Target { return 0; } "; var effect = new PixelShaderEffect(ShaderCompiler.CompileShader(hlsl, "ps_4_0")); using (var canvasDevice = new CanvasDevice()) using (var renderTarget = new CanvasRenderTarget(canvasDevice, 1, 1, 96)) using (var drawingSession = renderTarget.CreateDrawingSession()) { drawingSession.DrawImage(effect); } }
public void DrawChart() { if (_data == null || _data.Length <= 0) { return; } CanvasDevice device = CanvasDevice.GetSharedDevice(); //rendering options are calculating min & max values & value texts RenderingOptions renderingOptions = CreateRenderingOptions(_data); //_offscreenBackGround is created in here DrawBackGround(device, renderingOptions); //_offscreenChartImage is created in here DrawCharData(device, renderingOptions, _data); //forces re-draw ChartWin2DCanvas.Invalidate(); }
/// <summary> /// Helper metohd that crop a SoftwareBitmap given a new bounding box /// </summary> private SoftwareBitmap CropSoftwareBitmap(SoftwareBitmap softwareBitmap, float x, float y, float width, float height) { using (var resourceCreator = CanvasDevice.GetSharedDevice()) using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap)) using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, width, height, canvasBitmap.Dpi)) using (var drawingSession = canvasRenderTarget.CreateDrawingSession()) using (var cropEffect = new CropEffect()) { cropEffect.Source = canvasBitmap; drawingSession.DrawImage( cropEffect, new Rect(0.0, 0.0, width, height), new Rect(x, y, width, height), (float)1.0, CanvasImageInterpolation.HighQualityCubic); drawingSession.Flush(); return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Rgba8, (int)width, (int)height, BitmapAlphaMode.Premultiplied)); } }
private static async Task <CanvasBitmap> PickImageAsync() { CanvasBitmap result = null; var picker = new FileOpenPicker(); picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); var file = await picker.PickSingleFileAsync(); if (file != null) { using (var stream = await file.OpenReadAsync()) { result = await CanvasBitmap.LoadAsync(CanvasDevice.GetSharedDevice(), stream); } } return(result); }
//重新设置CanvasDevice和GraphicsDevice private void ResetDevices(bool IsDeviceLost) { try { if (IsDeviceLost) { _canvasDevice.DeviceLost -= _canvasDevice_DeviceLost; _canvasDevice = CanvasDevice.GetSharedDevice(); _canvasDevice.DeviceLost += _canvasDevice_DeviceLost; } //重新设置GraphicsDevice,在CanvasDevice丢失时会触发异常 CanvasComposition.SetCanvasDevice(_graphicsDevice, _canvasDevice); } catch (Exception e) when(_canvasDevice != null && _canvasDevice.IsDeviceLost(e.HResult)) { //通知设备已丢失,并触发CanvasDevice.DeviceLost _canvasDevice.RaiseDeviceLost(); } }
// Draw repeating pattern texture on backgound canvas. public async Task SetupBackgroundPatternAsync() { var compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; var canvasDevice = CanvasDevice.GetSharedDevice(); var graphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice); var bitmap = await CanvasBitmap.LoadAsync(canvasDevice, @"Assets\BackgroundPattern.png"); var drawingSurface = graphicsDevice.CreateDrawingSurface( bitmap.Size, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); using (var ds = CanvasComposition.CreateDrawingSession(drawingSurface)) { ds.Clear(Colors.Transparent); ds.DrawImage(bitmap); } var surfaceBrush = compositor.CreateSurfaceBrush(drawingSurface); surfaceBrush.Stretch = CompositionStretch.None; var border = new BorderEffect { ExtendX = CanvasEdgeBehavior.Wrap, ExtendY = CanvasEdgeBehavior.Wrap, Source = new CompositionEffectSourceParameter("source"), }; var fxFactory = compositor.CreateEffectFactory(border); var fxBrush = fxFactory.CreateBrush(); fxBrush.SetSourceParameter("source", surfaceBrush); var sprite = compositor.CreateSpriteVisual(); sprite.Size = new Vector2(4096); sprite.Brush = fxBrush; ElementCompositionPreview.SetElementChildVisual(_canvas, sprite); }
public static async Task <Uri> CreateCachedImageAsync(string internetUri, string saveName) { // Check that there is an image to save if (string.IsNullOrEmpty(internetUri)) { return(null); } try { // Create a canvas device using (var device = new CanvasDevice()) { // Create items used to same image to file var bitmap = await CanvasBitmap.LoadAsync(device, new Uri(internetUri)); // Create a renderer var renderer = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, bitmap.Dpi); // Draw the image using (var ds = renderer.CreateDrawingSession()) { ds.DrawImage(bitmap); } // Open the cache folder var cacheFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("cache", CreationCollisionOption.OpenIfExists); // Create a file var imageFile = await cacheFolder.CreateFileAsync(string.Format("{0}.jpg", saveName), CreationCollisionOption.OpenIfExists); // Write the image to the file using (var stream = await imageFile.OpenAsync(FileAccessMode.ReadWrite)) { await renderer.SaveAsync(stream, CanvasBitmapFileFormat.Png); return(new Uri(string.Format("ms-appdata:///local/cache/{0}.jpg", saveName), UriKind.Absolute)); } } } catch { return(null); } }
private async void SaveFile(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var canvas = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float)AnimatedCanvas.Size.Width, (float)AnimatedCanvas.Size.Height, 96); using (var canvasDS = canvas.CreateDrawingSession()) { DrawLocal(canvasDS, AnimatedCanvas.Size); DrawBitmap1(canvasDS, AnimatedCanvas.Size); DrawBitmap2(canvasDS, AnimatedCanvas.Size); DrawLines(canvasDS, AnimatedCanvas.Size); } var picker = new FileSavePicker(); picker.FileTypeChoices.Add("image", new List <string> { ".png" }); var file = await picker.PickSaveFileAsync(); if (file != null) { using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { var bytes = canvas.GetPixelBytes(); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, canvas.SizeInPixels.Width, canvas.SizeInPixels.Height, 96, 96, bytes); await encoder.FlushAsync(); } } }