private void SetColorAndDrawDots(CanvasDrawingSession drawingSession, Color colorGamer, Dot p) //Вспомогательная функция для DrawPoints. Выбор цвета точки в зависимости от ее состояния и рисование элипса { Color c; if (p.Blocked) { drawingSession.FillEllipse(p.x, p.y, PointWidth, PointWidth, Color.FromArgb(130, colorGamer.R, colorGamer.G, colorGamer.B)); } else if (last_move != null && p.x == last_move.x & p.y == last_move.y)//точка последнего хода должна для удоиства выделяться { drawingSession.FillEllipse(p.x, p.y, PointWidth, PointWidth, Color.FromArgb(140, colorGamer.R, colorGamer.G, colorGamer.B)); drawingSession.DrawEllipse(p.x, p.y, PointWidth / 2, PointWidth / 2, Colors.WhiteSmoke, 0.05f); drawingSession.DrawEllipse(p.x, p.y, PointWidth, PointWidth, colorGamer, 0.08f); } else { int G = colorGamer.G > 50 ? colorGamer.G - 50 : 120; c = p.BlokingDots.Count > 0 ? Color.FromArgb(255, colorGamer.R, colorGamer.G, colorGamer.B) : colorGamer; drawingSession.FillEllipse(p.x, p.y, PointWidth, PointWidth, colorGamer); drawingSession.DrawEllipse(p.x, p.y, PointWidth, PointWidth, c, 0.08f); } }
public void Draw(CanvasDrawingSession graphics) { if (DateTime.Now.Subtract(_shipBlewUp).TotalMilliseconds < 1000) { DrawShipBlowingup(graphics); } if (!_isActive) { return; } double rotation = _shipSprite.DirectionOfSprite.DegreesToRadians(); if (DateTime.Now.Subtract(_shipBlewUp).TotalMilliseconds > 1000) { //CreateShip(); DrawShip(rotation, graphics); DrawThruster(rotation, graphics); } }
/** * Draw the entire dancer's path as a translucent colored line * @param ds Canvas to draw to */ public void drawPath(CanvasDrawingSession ds) { if (pathpath == null) { var savebeat = lastbeat; CanvasPathBuilder pathBuilder = new CanvasPathBuilder(ds); animateComputed(0.0); var loc = location; pathBuilder.BeginFigure(loc.X, loc.Y); for (double beat = 0.1; beat <= beats; beat += 0.1) { animateComputed(beat); loc = location; pathBuilder.AddLine(loc.X, loc.Y); } pathBuilder.EndFigure(CanvasFigureLoop.Open); var cg = CanvasGeometry.CreatePath(pathBuilder); pathpath = CanvasCachedGeometry.CreateStroke(cg, 0.1f); animate(savebeat); // restore current position } ds.DrawCachedGeometry(pathpath, Color.FromArgb(80, fillColor.R, fillColor.G, fillColor.B)); }
//CreateResources is an event that is fired only when Win2D determines you need to recreate your visual resources, such as when the page is loaded. private void canvas_CreateResources(Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args) { CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { for (int i = 0; i < 100; i++) { clds.DrawText("Hello, World!", RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawCircle(RndPosition(), RndRadius(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); clds.DrawLine(RndPosition(), RndPosition(), Color.FromArgb(255, RndByte(), RndByte(), RndByte())); } } blur = new GaussianBlurEffect() { Source = cl, BlurAmount = 10.0f }; System.Diagnostics.Debug.WriteLine("Create" + ">>>" + j++); }
private void OnDraw(CanvasDrawingSession cds) { if (AxesCanDraw) { Render.OnDrawAxis(this, cds); } if (DataCanDraw) { Render.OnDrawSeries(this, cds); } if (MarkerCanDraw) { Render.OnDrawMarker(this, cds); } if (LegendCanDraw) { Render.OnDrawLegend(this, cds); } }
private static void FillDarkBackground(CanvasDrawingSession ds, Rect gridBackground) { Color black = Colors.Black; black.A = 128; float margin = 30; ds.FillRectangle( (float)gridBackground.X - margin, (float)gridBackground.Y - margin, (float)gridBackground.Width + margin + margin, (float)gridBackground.Height + margin + margin, black); margin = 10; black.A = 180; ds.FillRectangle( (float)gridBackground.X - margin, (float)gridBackground.Y - margin, (float)gridBackground.Width + margin + margin, (float)gridBackground.Height + margin + margin, black); }
private void DrawProgression(CanvasDrawingSession drawingSession, Size size, Rect relativeDestination) { var absoluteDestination = GetAbsoluteDestinationRect(size, relativeDestination); DrawTextPosition(drawingSession, _elevationTransform, _elevationPoints, tp => tp.Coordinate.Elevation.ToString("# m")); DrawTextPosition(drawingSession, _speedTransform, _speedPoints, tp => tp.Speed.ToString("# km/h")); DrawTextPosition(drawingSession, _cadenceTransform, _candencePoints, tp => tp.Cadence.ToString("0 tr/m")); var x = (float)(absoluteDestination.Left + _progression * absoluteDestination.Width); drawingSession.DrawLine(new Vector2(x, (float)absoluteDestination.Top), new Vector2(x, (float)absoluteDestination.Bottom), Colors.White, 2); // Distance var totalDistance = trackpoints[trackpoints.Length - 1].AccumulatedDistance.SiValue; var distanceKm = _progression * totalDistance / 1000; var whiteBrush = new CanvasSolidColorBrush(drawingSession, Colors.White); var position = new Vector2(x + 10, (float)absoluteDestination.Top); drawingSession.DrawText(distanceKm.ToString("#.## km"), position, whiteBrush, new CanvasTextFormat()); }
/// <summary> /// Draws a texture on the screen using the current X and Y coordinates. /// Increments Frame counters. /// </summary> /// <param name="draw">Session for drawing on the current frame</param> public void Draw(CanvasDrawingSession draw) { //Increments Frame counter FrameIndex++; if (FrameIndex >= AnimationSpeed) { FrameIndex = 0; Frame++; if (Frame >= this.textures.GetLength(0) || Frame >= this.bitmaps.GetLength(0)) { Frame = 0; } } //Prepares the bitmap to be drawn ICanvasImage bitmap = this.bitmaps[Frame]; //Lets abstract clases hook the bitmap modification for general purposes DrawAbstractModification(ref bitmap, draw); //Lets subclasses hook the bitmap modification DrawModification(ref bitmap, draw); if (bitmap == null) { return; } //Draw operation delegation to the Canvas Session on the current coordinates draw.DrawImage(bitmap, new Vector2(this.X, this.Y)); //Updates current description variables var size = this.bitmaps[Frame].Size; Width = size.Width; Height = size.Height; DrawHook(draw); }
public void Draw(CanvasDrawingSession ds) { int pointerPointIndex = 0; Vector2 prev = new Vector2(0, 0); const float penRadius = 10; foreach (Vector2 p in points) { if (pointerPointIndex != 0) { ds.DrawLine(prev, p, Colors.DarkRed, penRadius * 2); } ds.FillEllipse(p, penRadius, penRadius, Colors.DarkRed); prev = p; pointerPointIndex++; } if (points.Count > 0) { points.Dequeue(); } }
private void RenderThread(object parameter) { CanvasSwapChain swapChain = (CanvasSwapChain)parameter; using (MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateOrOpen("XboxGameBarPoc_SharedMemory", 0x644, MemoryMappedFileAccess.ReadWriteExecute)) { using (MemoryMappedViewAccessor viewAccessor = memoryMappedFile.CreateViewAccessor()) { using (Mutex mutex = new Mutex(false, "XboxGameBarPoc_Mutex")) { while (true) { try { mutex.WaitOne(); int count = 0; viewAccessor.Read <int>(0, out count); Box[] boxArray = new Box[count]; viewAccessor.ReadArray <Box>(4, boxArray, 0, count); using (CanvasDrawingSession ds = canvasSwapChainPanel.SwapChain.CreateDrawingSession(Colors.Transparent)) { for (int i = 0; i < boxArray.Length; i++) { ds.DrawRectangle(boxArray[i].X, boxArray[i].Y, boxArray[i].Width, boxArray[i].Height, Colors.Red); } } canvasSwapChainPanel.SwapChain.Present(); } finally { mutex.ReleaseMutex(); } } } } } }
public override void Draw(CanvasControl CanvasControl, CanvasDrawingSession ds, HSL HSL, Vector2 Center, float SquareHalfWidth, float SquareHalfHeight) { //Palette Rect rect = new Rect(Center.X - SquareHalfWidth, Center.Y - SquareHalfHeight, SquareHalfWidth * 2, SquareHalfHeight * 2); ds.FillRoundedRectangle(rect, 4, 4, new CanvasLinearGradientBrush(CanvasControl, Windows.UI.Colors.White, HSL.HSLtoRGB(HSL.H)) { StartPoint = new Vector2(Center.X - SquareHalfWidth, Center.Y), EndPoint = new Vector2(Center.X + SquareHalfWidth, Center.Y) }); ds.FillRoundedRectangle(rect, 4, 4, new CanvasLinearGradientBrush(CanvasControl, Windows.UI.Colors.Transparent, Windows.UI.Colors.Black) { StartPoint = new Vector2(Center.X, Center.Y - SquareHalfHeight), EndPoint = new Vector2(Center.X, Center.Y + SquareHalfHeight) }); ds.DrawRoundedRectangle(rect, 4, 4, Windows.UI.Colors.Gray); //Thumb float px = ((float)HSL.S - 50) * SquareHalfWidth / 50 + Center.X; float py = (50 - (float)HSL.L) * SquareHalfHeight / 50 + Center.Y; ds.DrawCircle(px, py, 8, Windows.UI.Colors.Black, 4); ds.DrawCircle(px, py, 8, Windows.UI.Colors.White, 2); }
private async Task <StorageFile> ExportCanvasAndImageAsync(StorageFile imageFile) { var saveFile = await GetImageToSaveAsync(); 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. FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(saveFile); return(saveFile); }
private void DrawBackImage(CanvasDrawingSession graphics, double scale) { if (_image != null) { Rect des = GetImageDrawingRect(); des.X *= scale; des.Y *= scale; des.Width *= scale; des.Height *= scale; // جلوه های فیلتر ICanvasImage image = GetBrightnessEffect(_image); //image = GetSharpenEffect(image); //image = GetBlurEffect(image); //image = GetStraightenEffect(image); //از الگوی فیلتر استفاده کنید image = ApplyFilterTemplate(image); graphics.DrawImage(image, des, _image.Bounds); } }
private void DrawIdleBg(CanvasDrawingSession ds) { Easings.ParamTween(ref BgY_c, BgY_t, 0.85f, 0.15f); BgFillRect.Y = BgY_c; Easings.ParamTween(ref BgR_c, BgR_t, 0.75f, 0.25f); if (BgR_c < 0) { ds.DrawImage(BgBmp, StageRect, BgFillRect); ds.FillRectangle(StageRect, MaskBrush); } else { ds.DrawImage(BgBmp, StageRect, BgFillRect); CanvasGeometry MaskFill = CanvasGeometry.CreateRectangle(ds, StageRect); CanvasGeometry DrillMask = CanvasGeometry.CreateCircle(ds, PCenter, BgR_c); CanvasGeometry Combined = MaskFill.CombineWith(DrillMask, Matrix3x2.CreateTranslation(0, 0), CanvasGeometryCombine.Exclude); ds.FillGeometry(Combined, MaskBrush); } }
void DrawInfo(CanvasDrawingSession ds) { var swapChain = swapChainManager.SwapChain; var size = swapChain.Size; var message = string.Format("{0:00}x{1:00} @{2:00}dpi", size.Width, size.Height, swapChain.Dpi); if (swapChain.Rotation != CanvasSwapChainRotation.None) { message += " " + swapChain.Rotation.ToString(); } ds.DrawText(message, size.ToVector2(), Colors.White, new CanvasTextFormat() { FontSize = 12, HorizontalAlignment = CanvasHorizontalAlignment.Right, VerticalAlignment = CanvasVerticalAlignment.Bottom }); if (currentPointsInContact.Count == 0) { ticksSinceLastTouch++; if (ticksSinceLastTouch > 100) { ds.DrawText("Touch the screen!", size.ToVector2() * 0.5f, Colors.White, new CanvasTextFormat() { FontSize = 24, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center }); } } else { ticksSinceLastTouch = 0; } }
/** * 1フレーム抽出 */ private void extractFrame(MediaPlayer mediaPlayer) { CanvasDevice canvasDevice = CanvasDevice.GetSharedDevice(); var canvasImageSrc = new CanvasImageSource(canvasDevice, (int)mThumbnailSize.Width, (int)mThumbnailSize.Height, 96 /*DisplayInformation.GetForCurrentView().LogicalDpi*/); using (SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Rgba8, (int)mThumbnailSize.Width, (int)mThumbnailSize.Height, BitmapAlphaMode.Ignore)) using (CanvasBitmap inputBitmap = CanvasBitmap.CreateFromSoftwareBitmap(canvasDevice, softwareBitmap)) using (CanvasDrawingSession ds = canvasImageSrc.CreateDrawingSession(Windows.UI.Colors.Black)) { try { mediaPlayer.CopyFrameToVideoSurface(inputBitmap); ds.DrawImage(inputBitmap); } catch (Exception e) { // 無視する Debug.WriteLine(e.ToString()); } CTX.Frames.Add(canvasImageSrc); } }
private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { EnsureResources(sender, sender.Size); currentDrawingSession = args.DrawingSession; bool needsTypographyHandler = needRefreshTypographyList || HighlightTypographyAffectedGlyphs; TypographyHandler typographyHandler = needsTypographyHandler ? new TypographyHandler(testString) : null; EnsureTypographyList(typographyHandler); EnsureTypography(); args.DrawingSession.DrawTextLayout(textLayout, 0, 0, Colors.LightBlue); if (HighlightTypographyAffectedGlyphs && CurrentTypographyOption.Name != CanvasTypographyFeatureName.None) { typographyHandler.CurrentMode = TypographyHandler.Mode.Highlight; typographyHandler.FeatureToHighlight = CurrentTypographyOption.Name; textLayout.DrawToTextRenderer(typographyHandler, 0, 0); } }
private void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { if (this.Content == null || this._pixels == null || this._pixelWidth <= 0 || this._pixelHeight <= 0) { args.DrawingSession.Clear(sender.ClearColor); } else { GeneralTransform transform = this.Content.TransformToVisual(sender); Vector2 location = transform.TransformPoint(new Point()).ToVector2(); using (CanvasCommandList cl = new CanvasCommandList(sender)) { using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { using (CanvasBitmap bitmap = CanvasBitmap.CreateFromBytes(sender, this._pixels, this._pixelWidth, this._pixelHeight, DirectXPixelFormat.B8G8R8A8UIntNormalized, DisplayInformation.GetForCurrentView().LogicalDpi)) { clds.DrawImage(bitmap, location); } } float translateX = (float)(Math.Cos(Math.PI / 180.0d * this.Direction) * this.Depth); float translateY = 0 - (float)(Math.Sin(Math.PI / 180.0d * this.Direction) * this.Depth); Transform2DEffect finalEffect = new Transform2DEffect() { Source = new ShadowEffect() { Source = cl, BlurAmount = this.BlurAmount, ShadowColor = this.GetShadowColor(), Optimization = this.Optimization }, TransformMatrix = Matrix3x2.CreateTranslation(translateX, translateY) }; args.DrawingSession.DrawImage(finalEffect); } } }
/// <summary> Override <see cref="PaletteBase.Draw"/>. </summary> public override void Draw(CanvasControl sender, CanvasDrawingSession ds, HSV hsv, Vector2 Center, float squareHalfWidth, float squareHalfHeight) { //Palette Rect rect = new Rect(Center.X - squareHalfWidth, Center.Y - squareHalfHeight, squareHalfWidth * 2, squareHalfHeight * 2); ds.FillRoundedRectangle(rect, 4, 4, new CanvasLinearGradientBrush(sender, Windows.UI.Colors.White, HSV.HSVtoRGB(hsv.H)) { StartPoint = new Vector2(Center.X - squareHalfWidth, Center.Y), EndPoint = new Vector2(Center.X + squareHalfWidth, Center.Y) }); ds.FillRoundedRectangle(rect, 4, 4, new CanvasLinearGradientBrush(sender, Windows.UI.Colors.Transparent, Windows.UI.Colors.Black) { StartPoint = new Vector2(Center.X, Center.Y - squareHalfHeight), EndPoint = new Vector2(Center.X, Center.Y + squareHalfHeight) }); ds.DrawRoundedRectangle(rect, 4, 4, Windows.UI.Colors.Gray); //Thumb float px = ((float)hsv.S - 50) * squareHalfWidth / 50 + Center.X; float py = (50 - (float)hsv.V) * squareHalfHeight / 50 + Center.Y; ds.DrawCircle(px, py, 9, Windows.UI.Colors.Black, 5); ds.DrawCircle(px, py, 9, Windows.UI.Colors.White, 3); }
private void PaintCursor(CanvasDrawingSession drawingSession, List <VirtualTerminal.Layout.LayoutRow> spans, CanvasTextFormat textFormat, TextPosition cursorPosition, Color cursorColor) { var cursorY = cursorPosition.Row; if (cursorY < 0 || cursorY >= Rows) { return; } var drawX = cursorPosition.Column * CharacterWidth; var drawY = (cursorY * CharacterHeight); if (cursorY < spans.Count) { var textRow = spans[cursorY]; drawingSession.Transform = Matrix3x2.CreateTranslation( 1.0f, (float)(textRow.DoubleHeightBottom ? -CharacterHeight : 0) ) * Matrix3x2.CreateScale( (float)(textRow.DoubleWidth ? 2.0 : 1.0), (float)(textRow.DoubleHeightBottom | textRow.DoubleHeightTop ? 2.0 : 1.0) ); drawY *= (textRow.DoubleHeightBottom | textRow.DoubleHeightTop) ? 0.5 : 1.0; } var cursorRect = new Rect( drawX, drawY, CharacterWidth, CharacterHeight + 0.9 ); drawingSession.DrawRectangle(cursorRect, cursorColor); }
private void GameCanvasUpdate(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args) { if (!ViewModel.IsGameInitialized || GameCanvas == null) { return; } try { ViewModel.UpdateGame(); RefreshGameSize(); InitializeOrRefreshDrawingSurface(); using (CanvasDrawingSession drawingSession = nextSurface.CreateDrawingSession()) { drawingSession.FillRectangle(new Rect(new Point(), nextSurface.Size), backgroundTileBrush); } if (gameWidth > gameHeight) { nextSurface.CopyPixelsFromBitmap(backgroundImageLandscape); nextSurface.CopyPixelsFromBitmap(ViewModel.PlayField, 32, 32); nextSurface.CopyPixelsFromBitmap(ViewModel.HudLandscape, 339, 26); } else { nextSurface.CopyPixelsFromBitmap(backgroundImagePortrait); nextSurface.CopyPixelsFromBitmap(ViewModel.PlayField, 32, 32); nextSurface.CopyPixelsFromBitmap(ViewModel.HudPortrait, 26, 339); } SwapSurfaces(); } catch (Exception ex) { Debug.WriteLine(ex); } }
/// <summary> ///Render image. /// </summary> /// <param name="size"> The size. </param> /// <param name="dpi"> The dpi. </param> /// <param name="isClearWhite"> Clears to the white color. </param> /// <returns> The image. </returns> public CanvasRenderTarget Render(float width, float height, float dpi, bool isClearWhite = true) { CanvasRenderTarget renderTarget = new CanvasRenderTarget(LayerManager.CanvasDevice, width, height, dpi); using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) { if (isClearWhite) { drawingSession.Clear(Colors.White); } ICanvasImage canvasImage = LayerBase.Render(LayerManager.CanvasDevice, LayerManager.RootLayerage); if ((canvasImage is null) == false) { int canvasWidth = this.CanvasTransformer.Width; int canvasHeight = this.CanvasTransformer.Height; if (canvasWidth == width && canvasHeight == height) { drawingSession.DrawImage(canvasImage); } else { float scaleX = width / canvasWidth; float scaleY = height / canvasHeight; Matrix3x2 matrix = Matrix3x2.CreateScale(scaleX, scaleY); drawingSession.DrawImage(new Transform2DEffect { InterpolationMode = CanvasImageInterpolation.HighQualityCubic, TransformMatrix = matrix, Source = canvasImage }); } } } return(renderTarget); }
Stack <IDrawingUI> _doodleUIs = new Stack <IDrawingUI>(); //涂鸦 private CanvasRenderTarget GetDrawings(bool edit) { double w, h; //画布大小 if (edit) //编辑状态 { w = MyCanvas.ActualWidth; h = MyCanvas.ActualHeight; } else { Rect des = GetImageDrawingRect(); w = (_image.Size.Width / des.Width) * MyCanvas.Width; h = (_image.Size.Height / des.Height) * MyCanvas.Height; } var scale = edit ? 1 : w / MyCanvas.Width; //缩放比例 CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget target = new CanvasRenderTarget(device, (float)w, (float)h, 96); using (CanvasDrawingSession graphics = target.CreateDrawingSession()) { //绘制背景 graphics.Clear(_back_color); //绘制底图 DrawBackImage(graphics, scale); //绘制贴图 if (_wall_paperUI != null) { _wall_paperUI.Draw(graphics, (float)scale); } } return(target); }
private void DrawBitmap2(CanvasDrawingSession ds, Size size) { if (bitmap2 != null) { var canvas = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), bitmap2.SizeInPixels.Width / 2, bitmap2.SizeInPixels.Height, 96); using (var canvasDS = canvas.CreateDrawingSession()) { var sourceRect = new Rect(bitmap2.SizeInPixels.Width * 0.25, 0, bitmap2.SizeInPixels.Width / 2, bitmap2.SizeInPixels.Height); canvasDS.DrawImage(bitmap2, new Rect(0, 0, canvas.SizeInPixels.Width, canvas.SizeInPixels.Height), sourceRect); } var effect = new SepiaEffect { Source = canvas }; var effect2 = new VignetteEffect { Amount = 1f, Source = effect }; var drawRect = new Rect(0, 0, size.Width / 2, size.Height); var canvasSourceRect = new Rect(0, 0, canvas.SizeInPixels.Width, canvas.SizeInPixels.Height); ds.DrawImage(effect2, drawRect, canvasSourceRect); } }
public async Task <StorageFile> DrawAsync() { if (!CheckResources()) { throw new ArgumentOutOfRangeException(); } var size = GetTileSize(); var device = CanvasDevice.GetSharedDevice(); var offscreen = new CanvasRenderTarget(device, (float)size.Width, (float)size.Height, 96); using (CanvasDrawingSession ds = offscreen.CreateDrawingSession()) { ds.Clear(Colors.Transparent); for (int i = 0; i < List.Count(); i++) { var todo = List[i]; ds.DrawTextLayout(CreateTextLayout(device, todo.Content), new Vector2(10f, 10 * i), new CanvasSolidColorBrush(device, Colors.White)); } } var cacheFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("LiveTile", CreationCollisionOption.OpenIfExists); var file = await cacheFolder.CreateFileAsync($"{TileKind.ToString()}.png", CreationCollisionOption.GenerateUniqueName); var bytes = offscreen.GetPixelBytes(); using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fs); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)size.Width, (uint)size.Height, 96, 96, bytes); await encoder.FlushAsync(); } return(file); }
public static void Apply() { App.Model.isCanUndo = false;//关闭撤销 var index = App.Model.Index; //新建渲染目标=>层 CanvasRenderTarget crt = new CanvasRenderTarget(App.Model.VirtualControl, App.Model.Width, App.Model.Height); using (CanvasDrawingSession ds = crt.CreateDrawingSession()) { ds.DrawImage(App.Model.SecondCanvasImage); } Layer l = new Layer { Visual = true, Opacity = 100, CanvasRenderTarget = crt, }; if (App.Model.isLowView) { l.LowView(); } else { l.SquareView(); } l.SetWriteableBitmap(App.Model.VirtualControl);//刷新缩略图 //Undo:撤销 Undo undo = new Undo(); undo.AddInstantiation(index); App.UndoAdd(undo); App.Model.Layers.Insert(index, l); App.Model.Index = index; App.Model.isCanUndo = true;//打开撤销 }
private void DrawMap(CanvasDrawingSession drawingSession, Size size, Rect destinationRelative) { if (_mapBounds == null) { return; } var destinationAbsolute = GetAbsoluteDestinationRect(size, destinationRelative); // Tracé sur la carte var mapGeometry = CreateMapGeometry(drawingSession, destinationAbsolute); var renderTarget = new CanvasRenderTarget(drawingSession, (float)destinationAbsolute.Width, (float)destinationAbsolute.Height); using (var session = renderTarget.CreateDrawingSession()) { session.DrawGeometry(mapGeometry, Colors.Red, 2); } // Transformation pour coller à la carte var transformMatrix = GetMapTransformationMatrix(destinationAbsolute); var transformEffect = new Transform2DEffect() { Source = renderTarget, TransformMatrix = transformMatrix, }; drawingSession.DrawImage(transformEffect, new Vector2(), destinationAbsolute); // Position sur la carte var totalDistance = trackpoints[trackpoints.Length - 1].AccumulatedDistance.SiValue; var targetDistance = _progression * totalDistance; var nearestTrackpoint = this.FindNearest(trackpoints, targetDistance); var centerCoordinates = GetMapPosition(nearestTrackpoint, destinationAbsolute); var transformedCoordinates = Multiply(transformMatrix, centerCoordinates); drawingSession.FillCircle(transformedCoordinates, 10, Colors.Black); }
protected override void DrawSelection(CanvasDrawingSession canvas) { if (selectedIndex < 0 || !legendShowing) { return; } byte alpha = (byte)(chartActiveLineAlpha * selectionA); float fullWidth = chartWidth / (pickerDelegate.pickerEnd - pickerDelegate.pickerStart); float offset = fullWidth * pickerDelegate.pickerStart - HORIZONTAL_PADDING; float xPoint = chartData.xPercentage[selectedIndex] * fullWidth - offset; selectedLinePaint.A = alpha; canvas.DrawLine(xPoint, 0, xPoint, (float)chartArea.Bottom, selectedLinePaint); int tmpN = lines.Count; for (int tmpI = 0; tmpI < tmpN; tmpI++) { LineViewData line = lines[tmpI]; if (!line.enabled && line.alpha == 0) { continue; } float yPercentage = (line.line.y[selectedIndex] * chartData.linesK[tmpI] - currentMinHeight) / (currentMaxHeight - currentMinHeight); float yPoint = MeasuredHeight - chartBottom - yPercentage * (MeasuredHeight - chartBottom - SIGNATURE_TEXT_HEIGHT); line.selectionPaint.A = (byte)(255 * line.alpha * selectionA); selectionBackgroundPaint.A = (byte)(255 * line.alpha * selectionA); canvas.FillCircle(xPoint, yPoint, line.selectionPaint); canvas.FillCircle(xPoint, yPoint, selectionBackgroundPaint); } }
private void RenderData(Size size, CanvasDrawingSession session, float[] values) { var canvasWidth = (float)size.Width; var canvasHeight = (float)size.Height; var localMin = values.Min(); var localMax = values.Max(); var localAvg = values.Average(); var scaleY = canvasHeight / values.Max(); var scaleX = canvasWidth / values.Length; using (var cpb = new CanvasPathBuilder(session)) { // first value cpb.BeginFigure(new Vector2(0, (canvasHeight - values[0] * scaleY))); //cpb.BeginFigure(new Vector2(0, values[0] * scaleY)); // values for (int i = 1; i < values.Length; i++) { cpb.AddLine(new Vector2(i * scaleX, (canvasHeight - values[i] * scaleY))); //cpb.AddLine(new Vector2(i * scaleX, values[i] * scaleY)); } if (renderArea) { cpb.AddLine(new Vector2(values.Count(), canvasHeight)); cpb.AddLine(new Vector2(0, canvasHeight)); cpb.EndFigure(CanvasFigureLoop.Closed); session.FillGeometry(CanvasGeometry.CreatePath(cpb), Colors.LightGreen); } else { cpb.EndFigure(CanvasFigureLoop.Open); session.DrawGeometry(CanvasGeometry.CreatePath(cpb), DataStrokeColor, DataStrokeThickness); } } }
protected override void DrawModification(ref ICanvasImage bitmap, CanvasDrawingSession draw) { base.DrawModification(ref bitmap, draw); //Uses the same draw strategies as its Owner foreach (IDrawModificationStrategy strategy in Owner.DrawModificationStrategies) { strategy.DrawModification(ref bitmap, draw); } //If there is a movement backwards, no movement actually happens if (IsMovingBack() && Owner.Direction.Horizontal == SpaceDirection.HorizontalDirection.NONE) { bitmap = null; return; } //If there is no relative movement, or a weak backwards movement with a sideways movement, thrust will blink //(it is always implicitly moving forward... this may be wrong in a boss battle in the case of a static background) if ( Owner.Direction == SpaceDirection.None || IsMovingBack() && Owner.Direction.Horizontal != SpaceDirection.HorizontalDirection.NONE ) { if (++BlinkCounter > BlinkPeriod) { BlinkCounter = 0; IsTurnedOn = !IsTurnedOn; if (!IsTurnedOn) { bitmap = null; return; } } } }
/// <summary></summary> public global::Windows.Foundation.Rect GetBounds(CanvasDrawingSession drawingSession) { throw new System.NotImplementedException(); }
private void DrawBackground(CanvasDrawingSession ds, Matrix3x2 transform) { const int levelUpTime = 60; // After levelling up we flash the screen white for a bit Color normalColor = Colors.Blue; Color levelUpFlashColor = Colors.White; var flashAmount = Math.Min(1, (leveledUpTimer / (float)levelUpTime)); ds.Clear(InterpolateColors(normalColor, levelUpFlashColor, flashAmount)); var topLeft = Vector2.Transform(new Vector2(0, 0), transform); var bottomRight = Vector2.Transform(new Vector2(1, 1), transform); var middle = (bottomRight.X - topLeft.X) / 2 + topLeft.X; // and display some text to let the player know what happened if (leveledUpTimer < levelUpTime * 2) { ds.DrawText("Level Up!", middle, 0, Colors.White, levelUpFormat); } // Draw some lines to show where the top / bottom of the play area is. var topLine = topLeft.Y - Letter.TextFormat.FontSize; var bottomLine = bottomRight.Y + Letter.TextFormat.FontSize; Color lineColor = levelUpFlashColor; lineColor.A = 128; ds.DrawLine(0, topLine, bottomRight.X, topLine, lineColor, 3); ds.DrawLine(0, bottomLine, bottomRight.X, bottomLine, lineColor, 3); }
public void Draw(CanvasDrawingSession ds, Size screenSize) { var transform = CalculateGameToScreenTransform(screenSize); DrawBackground(ds, transform); foreach (var letter in letters) { letter.Draw(ds, transform); } ds.Transform = Matrix3x2.Identity; if (!ThumbnailGenerator.IsDrawingThumbnail) { string scoreText = string.Format("Score: {0}", score); if (highScore != -1) { scoreText += string.Format(" ({0})", highScore); } ds.DrawText(scoreText, 0, 0, Colors.White, scoreFormat); } }
public void Draw(CanvasDrawingSession ds, Matrix3x2 transform) { var pos = Vector2.Transform(Pos, transform); var mu = (float)Math.Sin(DeadMu * Math.PI * 0.5); var scale = Matrix3x2.CreateScale(1.0f + mu * 10.0f); var center = new Vector2(pos.X, pos.Y); ds.Transform = Matrix3x2.CreateTranslation(-center) * scale * Matrix3x2.CreateTranslation(center); Color c = Color.FromArgb((byte)((1.0f - mu) * 255.0f), 255, 255, 255); ds.DrawText(Value.ToString(), pos, c, TextFormat); }