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); } } }
public void ProcessFrame(ProcessVideoFrameContext context) { var inputSurface = context.InputFrame.Direct3DSurface; var outputSurface = context.OutputFrame.Direct3DSurface; using (var inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, inputSurface)) using (var renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, outputSurface)) using (var ds = renderTarget.CreateDrawingSession()) using (var brush = new CanvasImageBrush(canvasDevice, inputBitmap)) using (var textCommandList = new CanvasCommandList(canvasDevice)) { using (var clds = textCommandList.CreateDrawingSession()) { clds.DrawText( "Win2D\nMediaClip", (float)inputBitmap.Size.Width / 2, (float)inputBitmap.Size.Height / 2, brush, new CanvasTextFormat() { FontSize = (float)inputBitmap.Size.Width / 5, FontWeight = new FontWeight() { Weight = 999 }, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center }); } var background = new GaussianBlurEffect() { BlurAmount = 10, BorderMode = EffectBorderMode.Hard, Source = new BrightnessEffect() { BlackPoint = new Vector2(0.5f, 0.7f), Source = new SaturationEffect() { Saturation = 0, Source = inputBitmap } } }; var shadow = new ShadowEffect() { Source = textCommandList, BlurAmount = 10 }; var composite = new CompositeEffect() { Sources = { background, shadow, textCommandList } }; ds.DrawImage(composite); } }
//CanvasControl raises Draw whenever your app needs to draw or redraw its content. private void canvas_Draw(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasDrawEventArgs 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())); } } GaussianBlurEffect blur1 = new GaussianBlurEffect(); blur1.Source = cl; blur1.BlurAmount = 10.0f; args.DrawingSession.DrawImage(blur1); }
private void Draw(CanvasControl sender, CanvasDrawEventArgs args) { if (_contentPresenter == null) { return; } Border border = VisualTreeHelper.GetChild(_contentPresenter, 0) as Border; if (border == null) { return; } Point borderPoint = border.TransformToVisual(this).TransformPoint(new Point(0, 0)); CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { clds.FillRoundedRectangle(new Rect(borderPoint.X, borderPoint.Y, border.ActualWidth, border.ActualHeight), (float)border.CornerRadius.TopLeft, (float)border.CornerRadius.TopLeft, Color.FromArgb(128, 0, 0, 0)); } Transform2DEffect shadowEffect = new Transform2DEffect { Source = new Transform2DEffect { Source = new ShadowEffect { BlurAmount = 2, ShadowColor = Color.FromArgb(160, 0, 0, 0), Source = cl }, TransformMatrix = Matrix3x2.CreateScale(1.0f, new Vector2((float)(border.ActualWidth / 2), ((float)border.ActualHeight / 2))) }, TransformMatrix = Matrix3x2.CreateTranslation(0, 1) }; args.DrawingSession.DrawImage(shadowEffect); }
private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { using (var session = args.DrawingSession) { foreach (var temp in FireflyParticle) { using (var cl = new CanvasCommandList(session)) using (var ds = cl.CreateDrawingSession()) { var c = temp.CenterColor; c.A = (byte)(temp.OpColor * 255); ds.FillCircle((float)temp.Point.X, (float)temp.Point.Y, (float)temp.Radius, c); using (var glow = new GlowEffectGraph()) { glow.Setup(cl, temp.Radius); session.DrawImage(glow.Blur); } } } } }
private void DoEffect(CanvasDrawingSession ds, Size size, float amount) { size.Width = size.Width - ExpandAmount; size.Height = size.Height - ExpandAmount; var offset = (float)(ExpandAmount / 2); using (var textLayout = CreateTextLayout(ds, size)) using (var textCommandList = new CanvasCommandList(ds)) { using (var textDs = textCommandList.CreateDrawingSession()) { textDs.DrawTextLayout(textLayout, 0, 0, GlowColor); } glowEffectGraph.Setup(textCommandList, amount); ds.DrawImage(glowEffectGraph.Output, offset, offset); ds.DrawTextLayout(textLayout, offset, offset, TextColor); } }
// 设置画笔(R:Radius) public void PaintSet(ICanvasResourceCreator rc, float R, Color co) { //Paint:绘画 Paint = new CanvasCommandList(rc); using (CanvasDrawingSession ds = Paint.CreateDrawingSession()) { ds.FillEllipse(0, 0, R, R, PaintBrush(rc, R, PaintHard, PaintOpacity, co)); } //Show:展示 var radius = (float)Math.Sqrt(R); PaintShow = new CanvasCommandList(rc); using (CanvasDrawingSession ds = PaintShow.CreateDrawingSession()) { ds.FillEllipse(0, 0, radius, radius, PaintBrush(rc, radius, PaintHard, PaintOpacity, Colors.White)); } }
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); } } }
//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++); }
public void Draw(ICanvasAnimatedControl sender, CanvasDrawingSession drawingSession) { if (currentThunder == null) { return; } // 保护原先画布的混合模式 var previousBlend = drawingSession.Blend; drawingSession.Blend = blendState; var builder = new CanvasPathBuilder(sender); builder.BeginFigure(0, 0); for (int i = 0; i < currentThunder.LifeLong; i++) { builder.AddLine(currentThunder.Path[i].X, currentThunder.Path[i].Y); } builder.EndFigure(CanvasFigureLoop.Open); builder.SetSegmentOptions(CanvasFigureSegmentOptions.ForceRoundLineJoin); // Draw the particle. var path = CanvasGeometry.CreatePath(builder); var NormalizeLifeTime = currentThunder.TimeSinceStart / currentThunder.Duration; byte opacity = (byte)((NormalizeLifeTime - 1) * (NormalizeLifeTime - 1) * 255); CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { clds.DrawGeometry(path, currentThunder.Position, Color.FromArgb((byte)(0.75f * opacity), 255, 255, 255), 6 * currentThunder.Luminace); } var lightAmount = 20.6f * currentThunder.Luminace * (NormalizeLifeTime - 1) * (NormalizeLifeTime - 1); blur.Source = cl; blur.BlurAmount = lightAmount; drawingSession.DrawImage(blur); drawingSession.DrawGeometry(path, currentThunder.Position, Color.FromArgb(opacity, 255, 240, 180), 2 * currentThunder.Luminace); drawingSession.Blend = previousBlend; if (NormalizeLifeTime > 1) { currentThunder = null; } }
public void DrawInkDoesNotModifyContextState() { Point[] points = { new Point(0, 0), new Point(100, 100), }; var strokeBuilder = new InkStrokeBuilder(); var stroke1 = strokeBuilder.CreateStroke(points); strokeBuilder.SetDefaultDrawingAttributes(new InkDrawingAttributes { Color = Colors.Yellow, DrawAsHighlighter = true }); var stroke2 = strokeBuilder.CreateStroke(points); using (var device = new CanvasDevice()) using (var target = new CanvasCommandList(device)) using (var drawingSession = target.CreateDrawingSession()) { var originalProperties = GetPropertyValues(drawingSession); drawingSession.DrawInk(new InkStroke[] { stroke1 }); var propertiesAfterDraw1 = GetPropertyValues(drawingSession); drawingSession.DrawInk(new InkStroke[] { stroke2 }); var propertiesAfterDraw2 = GetPropertyValues(drawingSession); CollectionAssert.AreEqual(originalProperties, propertiesAfterDraw1); CollectionAssert.AreEqual(originalProperties, propertiesAfterDraw2); } }
private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { if (this._bytes != null) { using (CanvasBitmap bitmap = CanvasBitmap.CreateFromBytes(sender, this._bytes, this._widthInPixels, this._heightInPixels, DirectXPixelFormat.B8G8R8A8UIntNormalized, this._dpi)) { clds.DrawImage(bitmap); } clds.FillRectangle(0, 0, this._widthInPixels, this._heightInPixels, this._maskColor); } else { clds.FillRectangle(0, 0, (float)sender.Size.Width, (float)sender.Size.Height, this._maskColor); } } this._effect.Source = cl; args.DrawingSession.DrawImage(this._effect); }
static ICanvasImage RealizeEffect(CanvasDevice device, TypeInfo effectType, IGraphicsEffect effect) { var dummySourceImage = new CanvasCommandList(device); // We can't realize an effect with invalid inputs, so must first set them all to something reasonable. foreach (var sourceProperty in effectType.DeclaredProperties.Where(p => p.PropertyType == typeof(IGraphicsEffectSource))) { sourceProperty.SetValue(effect, dummySourceImage); } // Add one image to any variable size Sources collection properties. foreach (var sourcesProperty in effectType.DeclaredProperties.Where(p => p.Name == "Sources")) { var sources = sourcesProperty.GetValue(effect) as IList <IGraphicsEffectSource>; sources.Clear(); sources.Add(dummySourceImage); } EffectAccessor.RealizeEffect(device, effect); return(dummySourceImage); }
private void canvasWin2d_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { CanvasCommandList ccl = new CanvasCommandList(sender); using (CanvasDrawingSession cds = ccl.CreateDrawingSession()) { // Loop over all the particles. for (int i = 0; i < maxParticles; i++) { // Draw cds.FillEllipse( (float)particles[i].newLeft, (float)particles[i].newTop, radius, radius, particles[i].col1 ); } } GaussianBlurEffect gb = new GaussianBlurEffect(); gb.Source = ccl; gb.BlurAmount = 5.0f; args.DrawingSession.DrawImage(gb); }
void CreateLinearGradient(ICanvasResourceCreator resourceCreator) { var commandList = new CanvasCommandList(resourceCreator); using (var drawingSession = commandList.CreateDrawingSession()) { var brush = new CanvasLinearGradientBrush(resourceCreator, Colors.White, Colors.Black) { StartPoint = new Vector2(-tigerSize.X / 4, 0), EndPoint = new Vector2(tigerSize.X * 5 / 4, 0), }; // Expand the bounds to avoid going past the edge of the gradient as we rotate it. var expandedBounds = new Rect((-tigerSize).ToPoint(), (tigerSize * 2).ToPoint()); drawingSession.FillRectangle(expandedBounds, brush); } linearGradient = new Transform2DEffect { Source = commandList }; }
//方法:设置(写到创建资源事件里) public void Set(ICanvasResourceCreator rc, float sx, float sy, ICanvasImage ci) { //放大 ScaleEffect se = new ScaleEffect { Source = ci, Scale = new Vector2(1 / sx, 1 / sy), InterpolationMode = CanvasImageInterpolation.NearestNeighbor, }; //剪裁四周的边线 var rect = se.GetBounds(rc); CropEffect sce = new CropEffect { Source = se, SourceRectangle = new Rect(2, 2, rect.Width - 4, rect.Height - 4), }; //恢复正常大小 CanvasCommandList ccl = new CanvasCommandList(rc); using (var ds = ccl.CreateDrawingSession()) { ds.Clear(Colors.Transparent); ds.DrawImage(sce); } //变成线框 Image = new LuminanceToAlphaEffect //亮度转不透明度 { Source = new EdgeDetectionEffect //边缘检测 { Amount = 1, Source = ccl }, }; }
private void OnWin2DDraw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { if (panel != null && gooeyButtonItemsProperty != null && property.BackgroundColor.HasValue) { var source = new CanvasCommandList(sender); using (var ds = source.CreateDrawingSession()) { ds.FillCircle(property.CenterPoint, (float)property.Radius - 1f, new CanvasSolidColorBrush(sender, property.BackgroundColor.Value) { Opacity = (float)property.Opacity }); foreach (var item in gooeyButtonItemsProperty) { if (item.BackgroundColor.HasValue) { ds.FillCircle(property.CenterPoint.X + (float)item.TranslateX, property.CenterPoint.Y + (float)item.TranslateY, (float)item.Radius, new CanvasSolidColorBrush(sender, item.BackgroundColor.Value) { Opacity = (float)item.Opacity }); } } } if (property.BlurAmount > 0) { effect.BlurAmount = (float)property.BlurAmount; effect.Source = source; args.DrawingSession.DrawImage(image); } else { args.DrawingSession.DrawImage(source); } } }
protected void DrawOuterCircle(CanvasControl sender, CanvasDrawEventArgs args) { var ds = args.DrawingSession; Color edgeColor = this.GaugeColor; if (IsLowAlarmEnabled && (Value <= LowAlarmValue) && IsOnline) { edgeColor = LowAlarmColor; } else if (IsLowWarningEnabled && (Value <= LowWarningValue) && IsOnline) { edgeColor = LowWarningColor; } else if (IsHighAlarmEnabled && (Value >= HighAlarmValue) && IsOnline) { edgeColor = HighAlarmColor; } else if (IsHighWarningEnabled && (Value >= HighWarningValue) && IsOnline) { edgeColor = HighWarningColor; } CanvasCommandList cl = new CanvasCommandList(sender); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { clds.DrawCircle(Center, OuterCircleRadius, edgeColor, outerCircleThickness); } GaussianBlurEffect blur = new GaussianBlurEffect(); blur.Source = cl; blur.BlurAmount = 3.0f; args.DrawingSession.DrawImage(blur); }
void CreateLinearGradient(ICanvasResourceCreator resourceCreator) { var commandList = new CanvasCommandList(resourceCreator); using (var drawingSession = commandList.CreateDrawingSession()) { var brush = new CanvasLinearGradientBrush(resourceCreator, Colors.White, Colors.Black) { StartPoint = new Vector2(-tigerSize.X / 4, 0), EndPoint = new Vector2(tigerSize.X * 5 / 4, 0), }; drawingSession.FillRectangle(bitmapTiger.Bounds, brush); } // Wrap the gradient with a border effect to avoid edge artifacts as we rotate it. linearGradient = new Transform2DEffect { Source = new BorderEffect { Source = commandList } }; }
private void DoPathEffect(CanvasControl sender, CanvasDrawingSession ds) { using (var thBuilder = new Microsoft.Graphics.Canvas.Geometry.CanvasPathBuilder(sender)) { var pthConverter = new PathToD2DPathGeometryConverter(); foreach (var path in _paths) { var offset = (float)ExpandAmount / 2; using (var cl = new CanvasCommandList(ds)) using (var pthGeo = pthConverter.parse(path, thBuilder)) { using (var clds = cl.CreateDrawingSession()) { clds.FillGeometry(pthGeo, 0, 0, GlowColor); } _eg.Setup(cl, (float)GlowAmount, GlowColor); ds.DrawImage(_eg.Output, offset, offset); ds.FillGeometry(pthGeo, offset, offset, ((SolidColorBrush)GlowFill).Color); } } } }
private void Draw(CanvasControl sender, CanvasDrawEventArgs args) { if (_contentPresenter == null) return; var border = VisualTreeHelper.GetChild(_contentPresenter, 0) as Border; if (border == null) return; var borderPoint = border.TransformToVisual(this).TransformPoint(new Point(0, 0)); var cl = new CanvasCommandList(sender); using (var clds = cl.CreateDrawingSession()) { clds.FillRoundedRectangle(new Rect(borderPoint.X, borderPoint.Y, border.ActualWidth, border.ActualHeight), (float)border.CornerRadius.TopLeft, (float)border.CornerRadius.TopLeft, Color.FromArgb(128, 0, 0, 0)); } var shadowEffect = new Transform2DEffect { Source = new Transform2DEffect { Source = new ShadowEffect { BlurAmount = 2, ShadowColor = Color.FromArgb(160, 0, 0, 0), Source = cl }, //TODO not doing any scaling right now, confirm with larger shadows TransformMatrix = Matrix3x2.CreateScale(1.0f, new Vector2((float)(border.ActualWidth / 2), ((float)border.ActualHeight / 2))) }, TransformMatrix = Matrix3x2.CreateTranslation(0, 1) }; args.DrawingSession.DrawImage(shadowEffect); // args.DrawingSession.DrawImage(cl); }
private async void DoStreamsEffect(CanvasControl sender, CanvasDrawingSession ds) { foreach (var stream in _streams) { var offset = (float)ExpandAmount / 2; using (var cl = new CanvasCommandList(ds)) { using (var clds = cl.CreateDrawingSession()) { stream.Seek(0); var canvasbmp = await CanvasBitmap.LoadAsync(sender, stream); clds.DrawImage(canvasbmp, 0, 0); } _eg.Setup(cl, (float)GlowAmount, GlowColor); ds.DrawImage(_eg.Output, offset, offset); } } }
public override CanvasCommandList GetChartImage() { if (Values == null || Values.GroupCount == 0 || Style?.ChartType != ChartType.Line) { return(null); } var style = (LineChartStyle)Style; var colorSpace = Style.ColorSpace.Select(ColorConverter.ConvertHexToColor).ToList(); var device = CanvasDevice.GetSharedDevice(); var commandList = new CanvasCommandList(device); using (var session = commandList.CreateDrawingSession()) { var titleLayout = ChartDrawHelper.CreateCanvasText(device, Values.Title, style.TitleFormat); var titleRect = titleLayout.LayoutBounds; if (Values.IsShowTitle) { session.DrawTextLayout(titleLayout, new Vector2(), ColorConverter.ConvertHexToColor(style.TitleFormat.Foreground)); } titleLayout.Dispose(); var maxValue = Values.Data.Select(o => o.Max()).Max(); var maxMarkerValue = (float)ValueFormatHelper.Ceiling(maxValue, 2); var axisGeo = ChartDrawHelper.GetAxis(device, style.AxisStyle, style.DataAreaWidth, maxMarkerValue); var axisRect = axisGeo.AxisLine.ComputeBounds(); axisRect.Union(axisGeo.AxisValueMarker.GetBounds(device)); var axisOffset = new Point((titleRect.Width - axisRect.Width) / 2 - axisRect.X, titleRect.Height + style.TitleFormat.Thickness.Bottom - axisRect.Y).ToVector2(); using (var axisCommandList = new CanvasCommandList(session)) { using (var axisDrawSession = axisCommandList.CreateDrawingSession()) { axisDrawSession.Transform = Matrix3x2.CreateTranslation(axisOffset); axisDrawSession.DrawGeometry(axisGeo.AxisLine, ColorConverter.ConvertHexToColor(style.AxisStyle.LineColor), style.AxisStyle.LineWidth); axisDrawSession.FillGeometry(axisGeo.AxisArrow, ColorConverter.ConvertHexToColor(style.AxisStyle.LineColor)); axisDrawSession.DrawImage(axisGeo.AxisValueMarker); } session.DrawImage(axisCommandList); } axisGeo.Dispose(); var maxValueHeight = maxValue / maxMarkerValue * axisGeo.DataRect.Height; var lineGeos = GetLineChart(device, style, Values.Data, (float)maxValueHeight, style.DataAreaWidth, style.DataLabelFormat, Style.ColorSpace); var dataOffset = axisOffset + new Point(axisGeo.DataRect.X, axisGeo.DataRect.Y + axisGeo.DataRect.Height) .ToVector2(); using (var dataCommandList = new CanvasCommandList(session)) { using (var drawSession = dataCommandList.CreateDrawingSession()) { drawSession.Transform = Matrix3x2.CreateTranslation(dataOffset); for (int i = 0; i < lineGeos.Count; i++) { drawSession.DrawGeometry(lineGeos[i].LineGeometry, colorSpace[i % colorSpace.Count], style.LineWidth); foreach (var dot in lineGeos[i].DotGeometries) { drawSession.FillGeometry(dot, colorSpace[i % colorSpace.Count]); } if (Values.IsShowDataValues) { drawSession.DrawImage(lineGeos[i].DataLabels); } lineGeos[i].Dispose(); } } session.DrawImage(dataCommandList); } if (Values.IsShowGroupLabels) { var markerPoints = new List <Vector2>(); var markerStrs = new List <string>(); var groupLength = style.DataAreaWidth / (Values.GroupCount - 1); for (int i = 0; i < Values.GroupCount; i++) { var markerPoint = new Vector2(i * groupLength, 0); markerPoints.Add(markerPoint); markerStrs.Add(Values.GroupLabels[i]); } var groupLabels = ChartDrawHelper.CreateValueMarker(device, style.GroupLabelFormat, markerPoints, markerStrs, MarkerPosition.Bottom); var groupLabelsOffset = axisOffset + new Vector2( style.AxisStyle.StartOffset, 0); using (var dataCommandList = new CanvasCommandList(session)) { using (var drawSession = dataCommandList.CreateDrawingSession()) { drawSession.Transform = Matrix3x2.CreateTranslation(groupLabelsOffset); drawSession.DrawImage(groupLabels); } session.DrawImage(dataCommandList); } groupLabels.Dispose(); } if (Values.IsShowLegend) { var legendLabels = Values.LegendItemLabels.Take(Values.LegendItemCount).ToList(); var legend = ChartDrawHelper.CreateLegend(device, style.LegendStyle, legendLabels, colorSpace, Values.LegendPosition); var legendRect = legend.GetBounds(device); switch (Values.LegendPosition) { case LegendPosition.Right: var rightOffset = new Point( axisOffset.X + axisRect.Width + style.LegendStyle.Thickness.Left - legendRect.X, axisOffset.Y - legendRect.Height - legendRect.Y) .ToVector2(); session.DrawImage(legend, rightOffset); break; case LegendPosition.Bottom: var bottomOffset = new Point( (titleRect.Width - legendRect.Width) / 2 - legendRect.X, axisOffset.Y + style.LegendStyle.Thickness.Top - legendRect.Y) .ToVector2(); session.DrawImage(legend, bottomOffset); break; } legend.Dispose(); } return(commandList); } }
private void CanvasControl_OnCreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args) { //init tanks InitTanks(); foreach (var tank in Tanks) { CanvasCommandList ccl = new CanvasCommandList(sender); using (CanvasDrawingSession cds = ccl.CreateDrawingSession()) { //draw each tank //tank base cds.DrawRectangle(new Rect(-tank.size / 2, -tank.size / 2, tank.size * 2, tank.size), FractionColors[tank.fraction]); //cannon cds.DrawRectangle(new Rect(-tank.size / 2, -tank.size / 2 + (tank.size / 1.5f), tank.size * 3, tank.size / 2), FractionColors[tank.fraction]); //"wheels" } //set the effect source tank.rotationEffect.Source = ccl; tank.translationEffect.Source = tank.rotationEffect; } CanvasCommandList pccl = new CanvasCommandList(sender); using (CanvasDrawingSession pds = pccl.CreateDrawingSession()) { pds.DrawCircle(0, 0, 5.0f, new CanvasSolidColorBrush(pds, Colors.Yellow)); } projectilePrototype.translationEffect = new Transform2DEffect(); projectilePrototype.translationEffect.Source = pccl; }
private void DoEffect(CanvasDrawingSession ds, Size size, float amount, Windows.UI.Color glowColor, Windows.UI.Color fillColor, double expandAmount) { var offset = (float)expandAmount / 2; //using (var textLayout = CreateTextLayout(ds, size)) using (var cl = new CanvasCommandList(ds)) { using (var clds = cl.CreateDrawingSession()) { clds.FillRectangle(0, 0, (float)size.Width, (float)size.Height, glowColor); } glowEffectGraph.Setup(cl, amount); ds.DrawImage(glowEffectGraph.Output, offset, offset); ds.FillRectangle(offset, offset, (float)size.Width, (float)size.Height, fillColor); } }
private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { var cl = new CanvasCommandList(sender); using (var clds = cl.CreateDrawingSession()) { if (_bytes != null) { using (var bitmap = CanvasBitmap.CreateFromBytes(sender, _bytes, _widthInPixels, _heightInPixels, DirectXPixelFormat.B8G8R8A8UIntNormalized, _dpi)) { clds.DrawImage(bitmap); } clds.FillRectangle(0, 0, _widthInPixels, _heightInPixels, _maskColor); } else { clds.FillRectangle(0, 0, (float)sender.Size.Width, (float)sender.Size.Height, _maskColor); } } _effect.Source = cl; args.DrawingSession.DrawImage(_effect); }
void DrawShadow(CanvasControl canvasCtrl, CanvasDrawingSession drawSession, List<ShadowParam> shadowParams) { var canvasCommandList = new CanvasCommandList(canvasCtrl); var content = _contentPresenter.Content as FrameworkElement; var contentWidth = content.ActualWidth + content.Margin.Left + content.Margin.Right; var contentHeight = content.ActualHeight + content.Margin.Top + content.Margin.Bottom; var radius = GetActualCornerRadius(contentWidth); double maxOffset_Y = shadowParams.Max(param => param.Offset_Y); _shadowCanvas.VerticalAlignment = content.VerticalAlignment; _shadowCanvas.HorizontalAlignment = content.HorizontalAlignment; using (var ds = canvasCommandList.CreateDrawingSession()) { ds.FillRoundedRectangle(new Rect(0, 0, contentWidth, contentHeight), radius, radius, Color.FromArgb(255, 0, 0, 0)); } CompositeEffect compositeEffect = CreateEffects(shadowParams, canvasCommandList); var bound = compositeEffect.GetBounds(drawSession); double shadowWidth = Math.Abs(bound.X); double shadowHeight = Math.Abs(bound.Y); UpdateLayout(maxOffset_Y, bound, shadowWidth, shadowHeight); DrawEffect(drawSession, compositeEffect, shadowWidth, shadowHeight); }
public static void DrawFunction( CanvasDrawingSession drawingSession, CancellationToken cancellationToken, IFunction function, Transform transform, bool isHighlighted) { string functionString = function.ToString(); QuadrantEventSource.Log.DrawFunctionStart(functionString); float interval = transform.DefaultInterval; float largeChangeThreshold = (transform.Top - transform.Bottom) / 20; float smallChangeThreshold = Math.Abs(transform.GetLogicalNormal(Vector2.UnitY).Y); float x = transform.Left; float difference = float.NaN; float previousY = float.NaN; float previousX = float.NaN; while (x <= transform.Right) { float y = (float)function.Function(x); if (!transform.IsOutsideVericalRange(y)) { using (var pathBuilder = new CanvasPathBuilder(drawingSession)) { if (previousY.IsReal()) { pathBuilder.BeginFigure(previousX, previousY); pathBuilder.AddLine(x, y); } else { pathBuilder.BeginFigure(x, y); } while (x <= transform.Right) { previousX = x; previousY = y; x += interval; y = (float)function.Function(x); if (!y.IsReal()) { break; } float previousDifference = difference; difference = y - previousY; float absoluteDifferece = Math.Abs(difference); bool isAsymptote = false; if (cancellationToken.IsCancellationRequested) { if (interval != transform.CanceledInterval) { interval = transform.CanceledInterval; QuadrantEventSource.Log.DrawFunctionCanceled(functionString); } } else if (absoluteDifferece > largeChangeThreshold) { if (interval > transform.MinimumInterval) { x = previousX; y = previousY; difference = previousDifference; interval = transform.MinimumInterval; continue; } if (!float.IsNaN(previousDifference) && (Math.Sign(difference) * Math.Sign(previousDifference)) < 0) { isAsymptote = true; } } else if (absoluteDifferece < smallChangeThreshold && interval < transform.DefaultInterval) { interval = Math.Min(2 * interval, transform.DefaultInterval); } bool shouldStartNewFigure = TryGetExitPoint(function, transform, x, y, isAsymptote, out Vector2 point); pathBuilder.AddLine(point); if (shouldStartNewFigure) { break; } } pathBuilder.EndFigure(CanvasFigureLoop.Open); using (var brush = new CanvasSolidColorBrush(drawingSession, function.Color)) using (CanvasGeometry geometry = CanvasGeometry.CreatePath(pathBuilder)) { CanvasGeometry transformedGeometry = geometry.Transform(transform.DisplayTransform); const float strokeWidth = 2; if (isHighlighted) { var highlightCommandList = new CanvasCommandList(drawingSession.Device); using (CanvasDrawingSession highlightDrawingSession = highlightCommandList.CreateDrawingSession()) { highlightDrawingSession.DrawGeometry( transformedGeometry, Vector2.Zero, brush, strokeWidth); } var shadowEffect = new ShadowEffect() { ShadowColor = function.Color, BlurAmount = 3, Source = highlightCommandList, Optimization = EffectOptimization.Speed }; drawingSession.DrawImage(shadowEffect); } drawingSession.DrawGeometry( transformedGeometry, Vector2.Zero, brush, strokeWidth); } } } if (y.IsReal() && previousY.IsReal()) { difference = y - previousY; } else { difference = float.NaN; } previousY = y; previousX = x; x += interval; } QuadrantEventSource.Log.DrawFunctionStop(); }
private async void OnSaveAsClicked(object sender, RoutedEventArgs e) { // the button should be disabled if there's no bitmap loaded Debug.Assert(virtualBitmap != null); var picker = new FileSavePicker(); picker.FileTypeChoices.Add("Jpegs", new List<string>() { ".jpg" }); var file = await picker.PickSaveFileAsync(); if (file == null) return; using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { // Stamp a big "Win2D" over the image before we save it, to demonstrate // that the image really has been processed. var device = CanvasDevice.GetSharedDevice(); var bounds = virtualBitmap.Bounds; var text = new CanvasCommandList(device); using (var ds = text.CreateDrawingSession()) { ds.DrawText("Win2D", bounds, Colors.White, new CanvasTextFormat() { VerticalAlignment = CanvasVerticalAlignment.Center, HorizontalAlignment = CanvasHorizontalAlignment.Center, FontFamily = "Comic Sans MS", FontSize = (float)(bounds.Height / 4) }); } var effect = new BlendEffect() { Background = virtualBitmap, Foreground = text, Mode = BlendEffectMode.Difference }; try { await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg); var message = string.Format("Finished saving '{0}'", file.Name); var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync(); } catch { var message = string.Format("Error saving '{0}'", file.Name); var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync(); } } }
public void EditRegionMask(List<Vector2> points, float zoomFactor) { if (regionMask == null) { // Demand-create our region mask image. regionMask = new CanvasRenderTarget(SourceBitmap.Device, Parent.Size.X, Parent.Size.Y, 96); } else { // Back up the previous mask, to support undo. previousRegionMask = currentRegionMask; } // Prepare an ICanvasImage holding the edit to be applied. ICanvasImage editMask; if (RegionSelectionMode == SelectionMode.MagicWand) { // Magic wand selection is already an image. editMask = GetMagicWandMask(points, zoomFactor); } else { // Capture selection geometry into a command list. var commandList = new CanvasCommandList(regionMask.Device); using (var drawingSession = commandList.CreateDrawingSession()) { // If this was just a touch without move, treat it as selecting the entire image. var dragRange = points.Select(point => Vector2.Distance(point, points[0])).Max() * zoomFactor; if (dragRange < 10) { drawingSession.Clear(Colors.White); } else { // Draw selection geometry. var geometry = GetSelectionGeometry(drawingSession, points); drawingSession.FillGeometry(geometry, Colors.White); } } editMask = commandList; } // Apply the edit. using (var drawingSession = regionMask.CreateDrawingSession()) { CanvasComposite compositeMode; switch (RegionSelectionOperation) { case SelectionOperation.Replace: drawingSession.Clear(Colors.Transparent); compositeMode = CanvasComposite.SourceOver; break; case SelectionOperation.Add: compositeMode = CanvasComposite.SourceOver; break; case SelectionOperation.Subtract: compositeMode = CanvasComposite.DestinationOut; break; case SelectionOperation.Invert: compositeMode = CanvasComposite.Xor; break; default: throw new NotSupportedException(); } drawingSession.DrawImage(editMask, Vector2.Zero, regionMask.Bounds, 1, CanvasImageInterpolation.Linear, compositeMode); } // Back up the mask, so we can recover from lost devices. currentRegionMask = regionMask.GetPixelBytes(); cachedRegionMask.Reset(); CanUndo = true; }
public void EditRegionMask(List <Vector2> points, float zoomFactor) { if (regionMask == null) { // Demand-create our region mask image. regionMask = new CanvasRenderTarget(SourceBitmap.Device, Parent.Size.X, Parent.Size.Y, 96); } else { // Back up the previous mask, to support undo. previousRegionMask = currentRegionMask; } // Prepare an ICanvasImage holding the edit to be applied. ICanvasImage editMask; if (RegionSelectionMode == SelectionMode.MagicWand) { // Magic wand selection is already an image. editMask = GetMagicWandMask(points, zoomFactor); } else { // Capture selection geometry into a command list. var commandList = new CanvasCommandList(regionMask.Device); using (var drawingSession = commandList.CreateDrawingSession()) { // If this was just a touch without move, treat it as selecting the entire image. var dragRange = points.Select(point => Vector2.Distance(point, points[0])).Max() * zoomFactor; if (dragRange < 10) { drawingSession.Clear(Colors.White); } else { // Draw selection geometry. var geometry = GetSelectionGeometry(drawingSession, points); drawingSession.FillGeometry(geometry, Colors.White); } } editMask = commandList; } // Apply the edit. using (var drawingSession = regionMask.CreateDrawingSession()) { CanvasComposite compositeMode; switch (RegionSelectionOperation) { case SelectionOperation.Replace: drawingSession.Clear(Colors.Transparent); compositeMode = CanvasComposite.SourceOver; break; case SelectionOperation.Add: compositeMode = CanvasComposite.SourceOver; break; case SelectionOperation.Subtract: compositeMode = CanvasComposite.DestinationOut; break; case SelectionOperation.Invert: compositeMode = CanvasComposite.Xor; break; default: throw new NotSupportedException(); } drawingSession.DrawImage(editMask, Vector2.Zero, regionMask.Bounds, 1, CanvasImageInterpolation.Linear, compositeMode); } // Back up the mask, so we can recover from lost devices. currentRegionMask = regionMask.GetPixelBytes(); cachedRegionMask.Reset(); CanUndo = true; }
private void canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args) { if (!svgSupported) { args.DrawingSession.Clear(Colors.Black); DrawNotSupportedMessage(args.DrawingSession, sender.Size); return; } Size viewportSize = new Size() { Width = 1000, Height = 1000 }; if (CurrentEffectType == EffectType.None) { args.DrawingSession.DrawSvg(svgDocument, viewportSize); } else if (CurrentEffectType == EffectType.EdgeDetection) { CanvasCommandList commandList = new CanvasCommandList(sender); using (var ds = commandList.CreateDrawingSession()) { ds.DrawSvg(svgDocument, viewportSize); } var edgeDetection = new EdgeDetectionEffect { Source = commandList, Amount = 1, BlurAmount = 1 }; args.DrawingSession.DrawImage(edgeDetection); } if (pointerDrag != null) { if (CurrentShapeType == ShapeType.Rectangle) { // Show ghost args.DrawingSession.DrawRectangle(pointerDrag.GetRectangle(), Colors.Magenta); } else if (CurrentShapeType == ShapeType.Ellipse) { var ellipse = pointerDrag.GetEllipse(); args.DrawingSession.DrawEllipse(ellipse.CenterX, ellipse.CenterY, ellipse.RadiusX, ellipse.RadiusY, Colors.Magenta); } else if (CurrentShapeType == ShapeType.Circle) { var circle = pointerDrag.GetCircle(); args.DrawingSession.DrawCircle(circle.Center, circle.Radius, Colors.Magenta); args.DrawingSession.DrawLine(circle.Center, pointerDrag.CurrentLocation.ToVector2(), Colors.Magenta); } else if (CurrentShapeType == ShapeType.Line) { args.DrawingSession.DrawLine(pointerDrag.StartLocation.ToVector2(), pointerDrag.CurrentLocation.ToVector2(), Colors.Magenta); } } }
private void DanmuCanvas_CreateResources(Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args) { cl = new CanvasCommandList(sender); }
private void DoPathEffect(CanvasControl sender, CanvasDrawingSession ds ) { using (var thBuilder = new Microsoft.Graphics.Canvas.Geometry.CanvasPathBuilder(sender)) { var pthConverter = new PathToD2DPathGeometryConverter(); foreach(var path in _paths) { var offset = (float)ExpandAmount / 2; using (var cl = new CanvasCommandList(ds)) using (var pthGeo = pthConverter.parse(path, thBuilder)) { using (var clds = cl.CreateDrawingSession()) { clds.FillGeometry(pthGeo,0,0, GlowColor); } _eg.Setup(cl, (float)GlowAmount, GlowColor); ds.DrawImage(_eg.Output, offset, offset); ds.FillGeometry(pthGeo,offset, offset, ((SolidColorBrush)GlowFill).Color); } } } }
//初始化特效渲染目标 public static void InitializeEffect() { //特效渲染目标 (上中下)(如果选区存在:选区选中的图像 ;否则:全部图像) using (CanvasDrawingSession ds = App.Model.SecondSourceRenderTarget.CreateDrawingSession()) { ds.Clear(Colors.Transparent); //获得当前图层的渲染目标 ds.DrawImage(App.Model.Layers[App.Model.Index].CanvasRenderTarget); //扣取选区的区域:如果有选区 if (App.Model.isAnimated == true) { ds.DrawImage(App.Model.MaskRenderTarget, 0, 0, App.Model.MaskRenderTarget.Bounds, 1, CanvasImageInterpolation.HighQualityCubic, CanvasComposite.DestinationIn); } } //下特效渲染目标 (从灰白网格到当前图层的下一层) using (CanvasDrawingSession ds = App.Model.SecondBottomRenderTarget.CreateDrawingSession()) { ds.DrawImage(App.GrayWhiteGrid); ICanvasImage ci = App.Model.NullRenderTarget; //由下向上渲染的图片接口 for (int i = App.Model.Layers.Count - 1; i > App.Model.Index; i--) //自下而上渲染 { ci = App.Render(App.Model.Layers[i], ci); //渲染 } ds.DrawImage(ci); //获得当前图层的扣掉图形的渲染目标 if (App.Model.isAnimated == true) { //复制源图 CanvasCommandList ccl = new CanvasCommandList(App.Model.VirtualControl); //渲染目标的画布布尔运算 using (CanvasDrawingSession dds = ccl.CreateDrawingSession()) { dds.DrawImage(App.Model.CurrentRenderTarget); dds.DrawImage(App.Model.MaskRenderTarget, 0, 0, App.Model.MaskRenderTarget.Bounds, 1, CanvasImageInterpolation.Linear, CanvasComposite.DestinationOut); } ds.DrawImage(ccl); } } //上特效渲染目标 (从当前图层的的上一层到顶层) using (CanvasDrawingSession ds = App.Model.SecondTopRenderTarget.CreateDrawingSession()) { ds.Clear(Colors.Transparent); //当前图层索引不在0,即并不在第一层 ICanvasImage ci = App.Model.NullRenderTarget; //当前图层索引不在1,即并不在第二层 if (App.Model.Index > 0) { for (int i = App.Model.Index - 1; i >= 0; i--) //自下而上渲染 { ci = App.Render(App.Model.Layers[i], ci); //渲染 } } ds.DrawImage(ci); } }
public override CanvasCommandList GetChartImage() { if (Values == null || Values.GroupCount == 0 || Style?.ChartType != ChartType.Pie) { return(null); } var style = (PieChartStyle)Style; var colorSpace = Style.ColorSpace.Select(ColorConverter.ConvertHexToColor).ToList(); var device = CanvasDevice.GetSharedDevice(); var commandList = new CanvasCommandList(device); using (var session = commandList.CreateDrawingSession()) { var geos = GetPieChart(device, Values.Data[0], style.DataLabelFormat, style.Radius, Values.IsShowDataValues); var titleLayout = ChartDrawHelper.CreateCanvasText(device, Values.Title, style.TitleFormat); var titleRect = titleLayout.LayoutBounds; if (Values.IsShowTitle) { session.DrawTextLayout(titleLayout, new Vector2(), ColorConverter.ConvertHexToColor(style.TitleFormat.Foreground)); } titleLayout.Dispose(); var diameter = style.Radius * 2 + style.BorderWidth / 2; var pieOffset = new Point((titleRect.Width - diameter) / 2, titleRect.Height + style.TitleFormat.Thickness.Bottom).ToVector2(); using (var pieCommandList = new CanvasCommandList(session)) { using (var pieDrawSession = pieCommandList.CreateDrawingSession()) { pieDrawSession.Transform = Matrix3x2.CreateTranslation(pieOffset); for (int i = 0; i < geos.Count; i++) { pieDrawSession.FillGeometry(geos[i].ShapeGeometry, colorSpace[i % Style.ColorSpace.Count]); } foreach (var t in geos) { pieDrawSession.DrawGeometry(t.ShapeGeometry, ColorConverter.ConvertHexToColor(style.BorderColor), style.BorderWidth, new CanvasStrokeStyle { LineJoin = CanvasLineJoin.Round, }); if (Values.IsShowDataValues) { pieDrawSession.FillGeometry(t.TextGeometry, (float)t.DataRect.X, (float)t.DataRect.Y, ColorConverter.ConvertHexToColor(style.DataLabelFormat.Foreground)); } t.Dispose(); } } session.DrawImage(pieCommandList); } if (Values.IsShowLegend) { var legendLabels = Values.GroupLabels.Take(Values.GroupCount).ToList(); var legend = ChartDrawHelper.CreateLegend(device, style.LegendStyle, legendLabels, colorSpace, Values.LegendPosition); var legendRect = legend.GetBounds(device); switch (Values.LegendPosition) { case LegendPosition.Right: var rightOffset = new Point( pieOffset.X + diameter + style.LegendStyle.Thickness.Left - legendRect.X, pieOffset.Y + (diameter - legendRect.Height) - legendRect.Y) .ToVector2(); session.DrawImage(legend, rightOffset); break; case LegendPosition.Bottom: var bottomOffset = new Point( (titleRect.Width - legendRect.Width) / 2 - legendRect.X, titleRect.Height + style.TitleFormat.Thickness.Bottom + diameter + style.LegendStyle.Thickness.Top - legendRect.Y) .ToVector2(); session.DrawImage(legend, bottomOffset); break; } legend.Dispose(); } } return(commandList); }
/// <summary> /// Renders text into a command list and sets this as the input to the flame /// effect graph. The effect graph must already be created before calling this method. /// </summary> private void SetupText(ICanvasResourceCreator resourceCreator) { textCommandList = new CanvasCommandList(resourceCreator); using (var ds = textCommandList.CreateDrawingSession()) { ds.Clear(Colors.Transparent); ds.DrawText( "Windows.UI.Composition", 0, 0, Colors.White, new Microsoft.Graphics.Canvas.Text.CanvasTextFormat { FontFamily = "Segoe UI", FontSize = 20, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Top }); } // Hook up the command list to the inputs of the flame effect graph. morphology.Source = textCommandList; composite.Sources[1] = textCommandList; }
private async void OnSaveAsClicked(object sender, RoutedEventArgs e) { // the button should be disabled if there's no bitmap loaded Debug.Assert(virtualBitmap != null); var picker = new FileSavePicker(); picker.FileTypeChoices.Add("Jpegs", new List <string>() { ".jpg" }); var file = await picker.PickSaveFileAsync(); if (file == null) { return; } using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { // Stamp a big "Win2D" over the image before we save it, to demonstrate // that the image really has been processed. var device = CanvasDevice.GetSharedDevice(); var bounds = virtualBitmap.Bounds; var text = new CanvasCommandList(device); using (var ds = text.CreateDrawingSession()) { ds.DrawText("Win2D", bounds, Colors.White, new CanvasTextFormat() { VerticalAlignment = CanvasVerticalAlignment.Center, HorizontalAlignment = CanvasHorizontalAlignment.Center, FontFamily = "Comic Sans MS", FontSize = (float)(bounds.Height / 4) }); } var effect = new BlendEffect() { Background = virtualBitmap, Foreground = text, Mode = BlendEffectMode.Difference }; try { await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg); var message = string.Format("Finished saving '{0}'", file.Name); var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync(); } catch { var message = string.Format("Error saving '{0}'", file.Name); var messageBox = new MessageDialog(message, "Virtual Bitmap Example").ShowAsync(); } } }
public static void Mask(ICanvasImage VirtualImage, ICanvasImage AnimatedImage, int MaskMode = 0, bool isClear = false) { CanvasComposite compositeMode = CanvasComposite.SourceOver; switch (MaskMode) { //主模式:SourceOver case 0: compositeMode = CanvasComposite.SourceOver; break; //加模式:SourceOver case 1: compositeMode = CanvasComposite.SourceOver; break; //减模式:DestinationOut case 2: compositeMode = CanvasComposite.DestinationOut; break; //差模式:DestinationIn case 3: compositeMode = CanvasComposite.DestinationIn; break; //负模式:DestinationIn case 4: compositeMode = CanvasComposite.Xor; break; default: break; } //画布 CanvasCommandList cl = new CanvasCommandList(App.Model.VirtualControl); //新图片(列表命令) using (CanvasDrawingSession ds = cl.CreateDrawingSession()) //新图片上画几何 { ds.Clear(App.Setting.MaskColor); ds.DrawImage(VirtualImage, 0, 0, App.Model.MaskRenderTarget.Bounds, 1, CanvasImageInterpolation.Linear, CanvasComposite.DestinationIn); } using (CanvasDrawingSession ds = App.Model.MaskRenderTarget.CreateDrawingSession())//旧图片上画旧图片(并布尔运算) { if (isClear == true || MaskMode == 0) { ds.Clear(Colors.Transparent); } ds.DrawImage(cl, 0, 0, App.Model.MaskRenderTarget.Bounds, 1, CanvasImageInterpolation.Linear, compositeMode); } //动画 CanvasCommandList acl = new CanvasCommandList(App.Model.AnimatedControl); //新图片(列表命令) using (CanvasDrawingSession ds = acl.CreateDrawingSession()) //新图片上画几何 { ds.Clear(App.Setting.MaskColor); ds.DrawImage(AnimatedImage, 0, 0, App.Model.MaskRenderTarget.Bounds, 1, CanvasImageInterpolation.Linear, CanvasComposite.DestinationIn); } using (CanvasDrawingSession ds = App.Model.MaskAnimatedTarget.CreateDrawingSession())//旧图片上画旧图片(并布尔运算) { if (isClear == true || MaskMode == 0) { ds.Clear(Colors.Transparent); } ds.DrawImage(acl, 0, 0, App.Model.MaskAnimatedTarget.Bounds, 1, CanvasImageInterpolation.Linear, compositeMode); } if (App.Model.isMask == true)//蓝色选区 { App.Model.isReRender = true; App.Model.Refresh++; } }
ICanvasImage WrapSourceWithIntermediateImage(PerDeviceResources resources, IntermediateMode mode) { switch (mode) { case IntermediateMode.ImageEffect: // We can either feed our graphics through an image effect... resources.SaturationEffect.Source = GetSourceBitmap(resources) ?? WrapSourceWithIntermediateImage(resources, IntermediateMode.None); resources.AddMessage("SaturationEffect ->\n"); return resources.SaturationEffect; case IntermediateMode.CommandList: var cl = new CanvasCommandList(resources.ResourceCreator); using (var ds = cl.CreateDrawingSession()) { DrawSourceGraphic(resources, ds, 0); } resources.AddMessage("CommandList ->\n"); return cl; case IntermediateMode.ImageEffectInCommandList: var cl2 = new CanvasCommandList(resources.ResourceCreator); using (var ds = cl2.CreateDrawingSession()) { ds.DrawImage(WrapSourceWithIntermediateImage(resources, IntermediateMode.ImageEffect)); } resources.AddMessage("CommandList ->\n"); return cl2; default: // ... or draw them into a rendertarget. var renderTarget = GetIntermediateRenderTarget(resources, mode); using (var ds = renderTarget.CreateDrawingSession()) { DrawSourceGraphic(resources, ds, 0); } var pixels = renderTarget.SizeInPixels; resources.AddMessage("RenderTarget (dpi: {0}, size: {1}, pixels: {2},{3}) ->\n", renderTarget.Dpi, renderTarget.Size, pixels.Width, pixels.Height); return renderTarget; } }
/// <summary> /// Renders text into a command list and sets this as the input to the flame /// effect graph. The effect graph must already be created before calling this method. /// </summary> private void SetupText(ICanvasResourceCreator resourceCreator) { textCommandList = new CanvasCommandList(resourceCreator); using (var ds = textCommandList.CreateDrawingSession()) { ds.Clear(Color.FromArgb(0, 0, 0, 0)); ds.DrawText( text, 0, 0, Colors.White, new CanvasTextFormat { FontFamily = "Segoe UI", FontSize = fontSize, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Top }); } // Hook up the command list to the inputs of the flame effect graph. morphology.Source = textCommandList; composite.Sources[1] = textCommandList; }
private async void btnUpload_Clicked(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); // Pick only one file once a time StorageFile file = await openPicker.PickSingleFileAsync(); if (file == null) { return; } using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) { cl = new CanvasCommandList(canvas); using (CanvasDrawingSession clds = cl.CreateDrawingSession()) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); clds.DrawImage( CanvasBitmap.CreateFromSoftwareBitmap(canvas, await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Premultiplied))); } blur = new GaussianBlurEffect { Source = cl, BlurAmount = (float)gaussianBlurAmountSlider.Value }; hueRotation = new HueRotationEffect { Source = blur, Angle = (float)hueRotationAmountSlider.Value / 100f * 360f }; contrast = new ContrastEffect { Source = hueRotation, Contrast = (float)(contrastAmountSlider.Value - 50f) / 50f }; saturation = new SaturationEffect { Source = contrast, Saturation = (float)saturationAmountSlider.Value / 100f }; temperatureAndTint = new TemperatureAndTintEffect { Source = saturation, Temperature = (float)(temperatureAmountSlider.Value - 50f) / 50f, Tint = (float)(tintAmountSlider.Value - 50f) / 50f }; grayscale = new GrayscaleEffect { Source = temperatureAndTint }; canvasEffect = saturation; // CanvasControl.Invalidate Method iIndicates that the contents of the CanvasControl need to be redrawn. // Calling Invalidate results in the Draw event being raised shortly afterward. // // Reference: https://microsoft.github.io/Win2D/html/M_Microsoft_Graphics_Canvas_UI_Xaml_CanvasControl_Invalidate.htm canvas.Invalidate(); gaussianBlurAmountSlider.IsEnabled = true; hueRotationAmountSlider.IsEnabled = true; contrastAmountSlider.IsEnabled = true; saturationAmountSlider.IsEnabled = true; temperatureAmountSlider.IsEnabled = true; tintAmountSlider.IsEnabled = true; grayscaleBufferPrevision.IsEnabled = true; var image = new BitmapImage(); await image.SetSourceAsync(fileStream); } }
/// <summary> /// Gets a specific rended-layer. /// </summary> /// <param name="resourceCreator"> The resource-creator. </param> /// <param name="layerage"> The layerage. </param> /// <returns> The rendered layer. </returns> public override ICanvasImage GetRender(ICanvasResourceCreator resourceCreator, Layerage layerage) { CanvasCommandList command = new CanvasCommandList(resourceCreator); using (CanvasDrawingSession drawingSession = command.CreateDrawingSession()) { if (this.Transform.IsCrop == false) { switch (base.Style.Transparency.Type) { case BrushType.LinearGradient: case BrushType.RadialGradient: case BrushType.EllipticalGradient: { Transformer transformer = base.Transform.Transformer; CanvasGeometry geometryCrop = transformer.ToRectangle(resourceCreator); ICanvasBrush canvasBrush = this.Style.Transparency.GetICanvasBrush(resourceCreator); using (drawingSession.CreateLayer(canvasBrush, geometryCrop)) { this.GetGeometryRender(resourceCreator, drawingSession, layerage); } } break; default: this.GetGeometryRender(resourceCreator, drawingSession, layerage); break; } } else { Transformer cropTransformer = base.Transform.CropTransformer; CanvasGeometry geometryCrop = cropTransformer.ToRectangle(resourceCreator); switch (base.Style.Transparency.Type) { case BrushType.LinearGradient: case BrushType.RadialGradient: case BrushType.EllipticalGradient: { ICanvasBrush canvasBrush = this.Style.Transparency.GetICanvasBrush(resourceCreator); using (drawingSession.CreateLayer(canvasBrush, geometryCrop)) { this.GetGeometryRender(resourceCreator, drawingSession, layerage); } } break; default: using (drawingSession.CreateLayer(1, geometryCrop)) { this.GetGeometryRender(resourceCreator, drawingSession, layerage); } break; } } } return(command); }
private ICanvasImage CreateNotSupportedMessage(string message) { var commandList = new CanvasCommandList(canvas); var textFormat = new CanvasTextFormat { FontSize = 16, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center }; using (var ds = commandList.CreateDrawingSession()) { ds.DrawText(message, bitmapTiger.Bounds, Colors.Red, textFormat); } animationFunction = elapsedTime => { }; return commandList; }
static void DrawTile(CanvasDrawingSession ds, float width, float height) { using (var cl = new CanvasCommandList(ds)) { using (var clds = cl.CreateDrawingSession()) { var text = string.Format("{0}\n{1}", DateTime.Now.ToString("ddd"), DateTime.Now.ToString("HH:mm")); var textFormat = new CanvasTextFormat() { FontFamily = "Segoe UI Black", HorizontalAlignment = CanvasHorizontalAlignment.Right, VerticalAlignment = CanvasVerticalAlignment.Center, FontSize = 20, LineSpacing = 20 }; clds.DrawText(text, 0, 0, Colors.White, textFormat); } var effect = new GaussianBlurEffect() { Source = cl, BlurAmount = 1, }; ds.Clear(Colors.Orange); var bounds = effect.GetBounds(ds); var ratio = bounds.Height / bounds.Width; var destHeight = height * ratio; ds.DrawImage(effect, new Rect(0, height / 2 - destHeight / 2, width, destHeight), bounds); ds.DrawText(string.Format("Generated by Win2D\n{0}\n{1}", DateTime.Now.ToString("d"), DateTime.Now.ToString("t")), 12, 12, Colors.Black, new CanvasTextFormat() { HorizontalAlignment = CanvasHorizontalAlignment.Left, VerticalAlignment = CanvasVerticalAlignment.Top, FontSize = 12 }); } }
private CompositeEffect CreateEffects(List<ShadowParam> shadowParams, CanvasCommandList canvasCommandList) { CompositeEffect compositeEffect = new CompositeEffect(); shadowParams.ForEach(param => { var shadowEffect = CreateShadowEffect(canvasCommandList, param); compositeEffect.Sources.Add(shadowEffect); }); return compositeEffect; }
/// <summary> /// Draws the entire game board for the provided state. /// </summary> /// <param name="sender"></param> /// <param name="session"></param> /// <param name="gameState"></param> public void Draw(ICanvasResourceCreator sender, double width, double height, CanvasDrawingSession session, GameTreeNode gameState) { // Calculations double clientWidth = width; double clientHeight = height; int boardWidth = this.SharedBoardControlState.BoardWidth; int widthWithBorder = boardWidth + (this.ShowCoordinates ? 2 : 0); int boardHeight = this.SharedBoardControlState.BoardHeight; Rect boardRectangle = RenderUtilities.Scale( new Rect(0, 0, clientWidth, clientHeight), boardWidth + (this.ShowCoordinates ? 2 : 0), boardHeight + (this.ShowCoordinates ? 2 : 0)); _cellSize = (int)(boardRectangle.Width / widthWithBorder); _halfSize = _cellSize / 2; if (this.ShowCoordinates) { _boardBorderThickness = _cellSize; } else { _boardBorderThickness = 0; } this.SharedBoardControlState.LeftPadding = (int)boardRectangle.X + _boardBorderThickness; this.SharedBoardControlState.TopPadding = (int)boardRectangle.Y + _boardBorderThickness; this.SharedBoardControlState.NewCellSize = _cellSize; // The above should only be probably called on demand, not always // Draw parts DrawBoard(session, clientWidth, clientHeight, boardRectangle); // Draw coordinates session.Transform = Matrix3x2.CreateTranslation( (float)boardRectangle.X, (float)boardRectangle.Y); DrawBoardCoordinates(sender, session, boardWidth, boardHeight); // Draw grid session.Transform = Matrix3x2.CreateTranslation( (float)boardRectangle.X + _boardBorderThickness, (float)boardRectangle.Y + _boardBorderThickness); CanvasCommandList lines = new CanvasCommandList(sender); using (CanvasDrawingSession linesSession = lines.CreateDrawingSession()) { linesSession.Antialiasing = CanvasAntialiasing.Aliased; DrawBoardLines(linesSession, boardWidth, boardHeight); } session.DrawImage(lines); DrawBoardStarPoints(session, boardWidth, boardHeight); lines.Dispose(); // Shining position special case if (_sharedBoardControlState.ShiningPosition.IsDefined) { int x = this.SharedBoardControlState.ShiningPosition.X; int y = ((this.SharedBoardControlState.BoardHeight - 1) - this.SharedBoardControlState.ShiningPosition.Y); float minusWhat = (float)_flickerPercentage * _cellSize * 0.07f; session.FillRoundedRectangle( _cellSize * x + minusWhat, _cellSize * y + minusWhat, _cellSize - 2 * minusWhat, _cellSize - 2 * minusWhat, 4, 4, Color.FromArgb(140, 100, 200, 100)); } // Draw all stones for given game state DrawStones(gameState, session); Position pointerPosition = _sharedBoardControlState.PointerOverPosition; // Mouse over position special case if (pointerPosition.IsDefined && _sharedBoardControlState.IsShadowDrawingEnabled) { if (SharedBoardControlState.IsAnalyzeModeEnabled) { // Set actual pointer position for the tools // This has to be done here and not in InputService because we might get caught in race condition // - pointerPosition.IsDefined returns true and in mean time user moves pointer outside of the board and IToolServices advertises Position.Undefined // - and finally in this step we ask ITool for its shadow. ITools should not worry about handling Position.Undefined for GetShadow SharedBoardControlState.AnalyzeToolServices.SetPointerPosition(pointerPosition); // Analyze mode is enabled, draw selected tool shadow item. DrawAnalyzeToolShadow(session, SharedBoardControlState.AnalyzeModeTool); } else { // TODO (future work) Petr : only if legal - use Ruleset IsLegalMove? // But it would be slow, you can implement caching to check for each intersection only once if (_sharedBoardControlState.PointerOverShadowColor != StoneColor.None && ( _sharedBoardControlState.TEMP_MoveLegality == null || _sharedBoardControlState.TEMP_MoveLegality[pointerPosition.X, pointerPosition.Y] == MoveResult.Legal)) { DrawStone(session, pointerPosition.X, pointerPosition.Y, _sharedBoardControlState.PointerOverShadowColor, 0.5); } } } // Draw markups if enabled if (SharedBoardControlState.IsAnalyzeModeEnabled) { session.Blend = CanvasBlend.SourceOver; DrawMarkups(session, gameState.Markups); } // Draw debug FPS session.Transform = Matrix3x2.Identity; if (!SimpleRenderService) { _fpsCounter.Draw(session, new Rect(clientWidth - 100, 10, 80, 30)); } }
async Task GenerateIcon(AppInfo appInfo, IconInfo iconInfo, StorageFolder folder) { // Draw the icon image into a command list. var commandList = new CanvasCommandList(device); using (var ds = commandList.CreateDrawingSession()) { appInfo.DrawIconImage(ds, iconInfo); } ICanvasImage iconImage = commandList; // Rasterize into a rendertarget. var renderTarget = new CanvasRenderTarget(device, iconInfo.Width, iconInfo.Height, 96); using (var ds = renderTarget.CreateDrawingSession()) { // Initialize with the appropriate background color. ds.Clear(iconInfo.TransparentBackground ? Colors.Transparent : appInfo.BackgroundColor); // Work out where to position the icon image. var imageBounds = iconImage.GetBounds(ds); imageBounds.Height *= 1 + iconInfo.BottomPadding; float scaleUpTheSmallerIcons = Math.Max(1, 1 + (60f - iconInfo.Width) / 50f); float imageScale = appInfo.ImageScale * scaleUpTheSmallerIcons; var transform = Matrix3x2.CreateTranslation((float)-imageBounds.X, (float)-imageBounds.Y) * Utils.GetDisplayTransform(renderTarget.Size.ToVector2(), new Vector2((float)imageBounds.Width, (float)imageBounds.Height)) * Matrix3x2.CreateScale(imageScale, renderTarget.Size.ToVector2() / 2); if (iconInfo.Monochrome) { // Optionally convert to monochrome. iconImage = new DiscreteTransferEffect { Source = new Transform2DEffect { Source = new LuminanceToAlphaEffect { Source = iconImage }, TransformMatrix = transform }, RedTable = new float[] { 1 }, GreenTable = new float[] { 1 }, BlueTable = new float[] { 1 }, AlphaTable = new float[] { 0, 1 } }; } else { ds.Transform = transform; // Optional shadow effect. if (appInfo.AddShadow) { var shadow = new ShadowEffect { Source = iconImage, BlurAmount = 12, }; ds.DrawImage(shadow); } } // draw the main icon image. ds.DrawImage(iconImage); } // Save to a file. using (var stream = await folder.OpenStreamForWriteAsync(iconInfo.Filename, CreationCollisionOption.ReplaceExisting)) { await renderTarget.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png); } }
static void ValidateCanDrawImage(CanvasDevice device, ICanvasImage image) { using (var commandList = new CanvasCommandList(device)) using (var drawingSession = commandList.CreateDrawingSession()) { drawingSession.DrawImage(image); } }
private void DoUIElementsEffect(CanvasControl sender, CanvasDrawingSession ds) { foreach (var elm in _uielements) { var offset = (float)ExpandAmount / 2; using (var cl = new CanvasCommandList(ds)) { using (var clds = cl.CreateDrawingSession()) { using (var canvasbmp = CanvasBitmap.CreateFromBytes(sender.Device, elm.Item1, elm.Item2, elm.Item3, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized)) { clds.DrawImage(canvasbmp, 0, 0); } } _eg.Setup(cl, (float)GlowAmount, GlowColor); ds.DrawImage(_eg.Output, offset + (float)elm.Item4, offset + (float)elm.Item5); } } }
private ICanvasImage CreateAlphaMask() { if (!AlphaMaskEffect.IsSupported) { return CreateNotSupportedMessage(requiresWin10_14393); } textLabel = requiresWin10_14393; // Draw an alpha gradient into a command list. var alphaGradientBrush = new CanvasRadialGradientBrush(canvas, Colors.Black, Colors.Transparent) { Center = bitmapTiger.Size.ToVector2() / 2, RadiusX = (float)bitmapTiger.Size.Width, RadiusY = (float)bitmapTiger.Size.Height }; var alphaMask = new CanvasCommandList(canvas); using (var drawingSession = alphaMask.CreateDrawingSession()) { drawingSession.FillRectangle(bitmapTiger.Bounds, alphaGradientBrush); } // Apply the alpha mask to the tiger bitmap. var alphaMaskEffect = new AlphaMaskEffect { Source = bitmapTiger, AlphaMask = alphaMask }; // Composite the alpha masked image on top of a background checker pattern. var compositeEffect = new CompositeEffect { Sources = { CreateCheckeredBackground(), alphaMaskEffect } }; animationFunction = elapsedTime => { }; return compositeEffect; }
static void DrawSecondsText(CanvasDrawingSession ds, Vector2 pos, int seconds) { // The text is drawn via a command list so we can use DrawImage to specify a difference CanvasComposite mode. using (var cl = new CanvasCommandList(ds)) { using (var clds = cl.CreateDrawingSession()) { clds.DrawText(seconds.ToString(), Vector2.Zero, Colors.White, textFormat); } Rect textBounds = cl.GetBounds(ds); var offset = new Vector2((float)textBounds.Left, (float)textBounds.Top); ds.DrawImage(cl, pos + offset, cl.GetBounds(ds), 1, CanvasImageInterpolation.NearestNeighbor, CanvasComposite.MaskInvert); } }
private CanvasCommandList GenerateTextDisplay(ICanvasResourceCreator resourceCreator, float width, float height) { var cl = new CanvasCommandList(resourceCreator); using (var ds = cl.CreateDrawingSession()) { float top = height - offset; float center = width / 4.0f; float symbolPos = center - 5.0f; float labelPos = center + 5.0f; for (int i = firstLine; i < lastLine; ++i) { float y = top + lineHeight * i; int index = i; if (index < characters.Length) { ds.DrawText(string.Format("{0}", (char)characters[index].Code), symbolPos, y, Colors.White, symbolText); ds.DrawText(string.Format("0x{0:X} - {1}", characters[index].Code, characters[index].Label), labelPos, y, Colors.White, labelText); } } } return cl; }
void CreateRadialGradient(ICanvasResourceCreator resourceCreator) { radialGradient = new CanvasCommandList(resourceCreator); using (var drawingSession = radialGradient.CreateDrawingSession()) { var sqrt2 = (float)Math.Sqrt(2); var brush = new CanvasRadialGradientBrush(resourceCreator, Colors.White, Colors.Black) { Center = tigerSize / 2, RadiusX = tigerSize.X / sqrt2, RadiusY = tigerSize.Y / sqrt2, }; drawingSession.FillRectangle(bitmapTiger.Bounds, brush); } }