public BlendEffectProcessor() { SetDefaultParameters(); m_blendEffect = new BlendEffect(); SetupEffectCategory(m_blendEffect); AddEditors(); }
private CompositionEffectBrush BuildBlurBrush(Compositor c, float blurAmount, Color maskColor) { var blurDesc = new GaussianBlurEffect { Name = "GlassBlur", BlurAmount = blurAmount, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("Source") }; var colorDesc = new ColorSourceEffect { Name = "GlassColor", Color = maskColor, }; var blendEffectDesc = new BlendEffect { Mode = BlendEffectMode.Multiply, Background = blurDesc, Foreground = colorDesc, }; var blurBrush = c.CreateEffectFactory(blendEffectDesc, new[] { "GlassBlur.BlurAmount", "GlassColor.Color" }).CreateBrush(); blurBrush.SetSourceParameter("Source", c.CreateBackdropBrush()); return blurBrush; }
private void ApplyBlur() { var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.Multiply, Background = new ColorSourceEffect { Name = "Tint", Color = Colors.White }, Foreground = new GaussianBlurEffect { Name = "Blur", Source = new CompositionEffectSourceParameter("Backdrop"), BlurAmount = BlurAmount, BorderMode = EffectBorderMode.Hard } }; var blurEffectFactory = _compositor.CreateEffectFactory(graphicsEffect, new List <string> { "Blur.BlurAmount", "Tint.Color" }); var brush = blurEffectFactory.CreateBrush(); var destinationBrush = _compositor.CreateBackdropBrush(); brush.SetSourceParameter("Backdrop", destinationBrush); var blurSprite = _compositor.CreateSpriteVisual(); blurSprite.Size = new Vector2((float)BlurContentPresenter.ActualWidth, (float)BlurContentPresenter.ActualHeight); blurSprite.Brush = brush; ElementCompositionPreview.SetElementChildVisual(BlurContentPresenter, blurSprite); }
public BlendEffectProcessor() { SetDefaultParameters(); m_blendEffect = new BlendEffect(); SetupEffectCategory(m_blendEffect); AddEditors(); }
private ICanvasImage CreateBlend() { var rotatedTiger = new Transform3DEffect { Source = bitmapTiger }; var blendEffect = new BlendEffect { Background = bitmapTiger, Foreground = rotatedTiger }; // Animation swings the second copy of the image back and forth, // while cycling through the different blend modes. int enumValueCount = Utils.GetEnumAsList <BlendEffectMode>().Count; animationFunction = elapsedTime => { blendEffect.Mode = (BlendEffectMode)(elapsedTime / Math.PI % enumValueCount); textLabel = "Mode: " + blendEffect.Mode; rotatedTiger.TransformMatrix = Matrix4x4.CreateRotationZ((float)Math.Sin(elapsedTime)); }; return(blendEffect); }
private CompositionEffectBrush BuildColoredBlurBrush() { var gaussianBlur = new GaussianBlurEffect { Name = "Blur", Source = new CompositionEffectSourceParameter("source"), BlurAmount = 15.0f, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced }; var colorEffect = new ColorSourceEffect { Name = "ColorSource2", Color = (Color)App.Current.Resources["KlivaMainColor"] }; var blendEffect = new BlendEffect { Mode = BlendEffectMode.Multiply, Background = gaussianBlur, Foreground = colorEffect }; var factory = m_compositor.CreateEffectFactory(blendEffect); var brush = factory.CreateBrush(); return(brush); }
private CompositionEffectBrush CreateBlurBrush() { var blurEffect = new GaussianBlurEffect { Name = "Blur", BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("Source"), BlurAmount = 0 }; var blendEffect = new BlendEffect { Background = blurEffect, Foreground = new ColorSourceEffect { Name = "Color", Color = Colors.Transparent }, Mode = BlendEffectMode.LighterColor }; var saturationEffect = new SaturationEffect { Source = blendEffect, Saturation = 1.75f }; var effectFactory = _compositor.CreateEffectFactory(saturationEffect, new[] { "Blur.BlurAmount", "Color.Color" }); var effectBrush = effectFactory.CreateBrush(); return(effectBrush); }
public BasicUsePage() { this.InitializeComponent(); SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; SystemNavigationManager.GetForCurrentView().BackRequested += (o, e) => { Frame.Navigate(typeof(MainPage), ImageElement.Source); }; this.PropertyChanged += (o, e) => { SetUpRenderingChain(); ImageElement.Render(); }; logoEffect = new BlendEffect(); logoEffect.ForegroundSource = ImageResourceProvider.NTKLogo; logoEffect.TargetArea = new Rect(0.9, 0.9, 0.1, 0.1); logoEffect.TargetOutputOption = OutputOption.PreserveAspectRatio; bozjakHeadshotEffect = new BlendEffect(); bozjakHeadshotEffect.ForegroundSource = ImageResourceProvider.BozjakHeadshot; bozjakHeadshotEffect.TargetArea = new Rect(0.05, 0.05, 0.2, 0.2); bozjakHeadshotEffect.TargetOutputOption = OutputOption.PreserveAspectRatio; blurEffect = new BlurEffect(); }
public static IImageProvider Generate(IImageProvider objectMaskSource, LinearGradient gradient, Size size, IReadOnlyList <ILensBlurKernel> kernels) { var backgroundSource = new GradientImageSource(size, gradient); var blendEffect = new BlendEffect(backgroundSource, objectMaskSource, BlendFunction.Lighten); return(new IndexRemappingEffect(blendEffect, kernels.Count + 2)); }
public BackDrop() { visual = ElementCompositionPreview.GetElementVisual(this); compositor = visual.Compositor; blurredVisual = compositor.CreateSpriteVisual(); var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.HardLight, Background = new ColorSourceEffect() { Name = "Tint", Color = Color.FromArgb(175, 0, 0, 0), }, Foreground = new GaussianBlurEffect() { Name = "Blur", Source = new CompositionEffectSourceParameter("source"), BlurAmount = 10f, Optimization = EffectOptimization.Balanced, BorderMode = EffectBorderMode.Hard, } }; effectFactory = compositor.CreateEffectFactory(graphicsEffect); var effectBrush = effectFactory.CreateBrush(); effectBrush.SetSourceParameter("source", compositor.CreateBackdropBrush()); blurredVisual.Brush = effectBrush; ElementCompositionPreview.SetElementChildVisual(this, blurredVisual); this.SizeChanged += BackDrop_SizeChanged; }
private CompositionEffectBrush BuildBlurBrush() { GaussianBlurEffect blurEffect = new GaussianBlurEffect() { Name = "Blur", BlurAmount = 0.0f, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced }; blurEffect.Source = new CompositionEffectSourceParameter("source"); BlendEffect effect = new BlendEffect { Foreground = new ColorSourceEffect { Name = "Color", Color = Colors.Transparent }, Background = blurEffect, Mode = BlendEffectMode.Multiply }; var factory = Compositor.CreateEffectFactory( effect, new[] { "Blur.BlurAmount", "Color.Color" } ); return(factory.CreateBrush()); }
private async Task CreateResourcesAsync(CanvasControl sender) { m_BackgroundImage = await CanvasBitmap.LoadAsync(sender.Device, new Uri("ms-appx:///Assets/setup_bg.jpg")); //m_BackgroundImageInitialAlpha = await CanvasBitmap.LoadAsync(sender.Device, new Uri("ms-appx:///Assets/nuki_initial.png")); var blured = new GaussianBlurEffect() { Source = m_BackgroundImage, BlurAmount = 10.0f, }; m_BluredBackground = new BlendEffect() { Background = blured, Foreground = new ColorSourceEffect() { Color = Windows.UI.Color.FromArgb(25, 0, 0, 0) }, Mode = BlendEffectMode.Darken }; m_BlendedBackground = new BlendEffect() { Background = blured, Foreground = new ColorSourceEffect() { Color = Windows.UI.Color.FromArgb(100, 0, 0, 0) }, Mode = BlendEffectMode.Darken }; m_ImageStatus = ImageLoadStatus.Fading; sender.Invalidate(); }
private CompositionEffectBrush CreateBlurBrush() { var blurEffect = new GaussianBlurEffect() { Name = "BlurEffect", BlurAmount = (float)BlurAmount, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("Source"), BorderMode = EffectBorderMode.Hard }; var colorEffect = new ColorSourceEffect() { Name = "ColorEffect", Color = TintColor }; var blendEffect = new BlendEffect() { Background = blurEffect, Foreground = colorEffect, Mode = BlendEffectMode.SoftLight }; var effectFactory = _compositor.CreateEffectFactory(blendEffect, new[] { "BlurEffect.BlurAmount", "ColorEffect.Color" }); return(effectFactory.CreateBrush()); }
private CompositionEffectBrush BuildBlurBrush() { var blurEffect = new GaussianBlurEffect { Name = "Blur", BlurAmount = 0.0f, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("Source") }; var blendEffect = new BlendEffect { Background = blurEffect, Foreground = new ColorSourceEffect { Name = "Color", Color = Color.FromArgb(90, 255, 255, 255) }, Mode = BlendEffectMode.SoftLight }; var saturationEffect = new SaturationEffect { Name = "Saturation", Source = blendEffect, Saturation = 1.75f }; var factory = _compositor.CreateEffectFactory( saturationEffect, new[] { "Blur.BlurAmount", "Color.Color", "Saturation.Saturation" }); return(factory.CreateBrush()); }
private static CompositionBrush CreateBlurBrush() { if (_blurBrush != null) { return(_blurBrush); } var blurEffect = new GaussianBlurEffect { Name = "Blur", BlurAmount = 15.0f, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("source") }; var blendEffect = new BlendEffect { Background = blurEffect, Foreground = new ColorSourceEffect { Name = "Color", Color = Color.FromArgb(64, 0, 0, 0) }, Mode = BlendEffectMode.SoftLight }; var blurEffectFactory = _compositor.CreateEffectFactory(blendEffect); var blurBrush = blurEffectFactory.CreateBrush(); var backdropBrush = _compositor.CreateBackdropBrush(); blurBrush.SetSourceParameter("source", backdropBrush); _blurBrush = blurBrush; return(_blurBrush); }
private static Layer CompositeUnsorted(params Layer[] layers) { if (layers.Length == 0) { return(null); } if (layers.Length == 1) { return((Layer)layers[0].Clone()); } Layer @base = layers[0]; bool valid = layers.Aggregate(true, (b, layer) => b && layer.Width == @base.Width && layer.Height == @base.Height); if (!valid) { throw new Exception("Layer Sizes Mismatch"); } Layer tgtLyr = Layer.Create(@base.Width, @base.Height); BlendEffect effect = new BlendEffect(); foreach (Layer t in layers) { Rectangle area = t.GetArea(); area.Inflate(1, 1); effect.OverlayLayer = t; effect.Region = area; effect.ApplyEffect(tgtLyr); } return(tgtLyr); }
private async void DialController_ButtonClicked(RadialController sender, RadialControllerButtonClickedEventArgs args) { try { ShowBusyIndicator("saving file..."); 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)) { // watermark the image var device = CanvasDevice.GetSharedDevice(); var bounds = virtualBitmap.Bounds; var text = new CanvasCommandList(device); using (var ds = text.CreateDrawingSession()) { ds.DrawText("Created by Dial-In", bounds, Colors.White, new CanvasTextFormat { VerticalAlignment = CanvasVerticalAlignment.Bottom, HorizontalAlignment = CanvasHorizontalAlignment.Right, FontFamily = "Segoe UI", FontSize = (float)(bounds.Height / 12) }); } var effect = new BlendEffect() { Background = virtualBitmap, Foreground = text, Mode = BlendEffectMode.Difference }; // save the image to final file await CanvasImage.SaveAsync(effect, bounds, 96, device, stream, CanvasBitmapFileFormat.Jpeg); } } catch (Exception ex) { await new MessageDialog($"Something went wrong saving the image: {ex}", "Exception").ShowAsync(); } finally { HideBusyIndicator(); } }
public BlendEffectProcessor(IImageProvider source) { SetDefaultParameters(); m_blendEffect = new BlendEffect(); // SetupEffectCategory(m_blendEffect); m_blendEffect.Source = source; AddEditors(); }
//@Static /// <summary> /// Render layers. /// </summary> /// <param name="resourceCreator"> The resource-creator. </param> /// <param name="layerages"> The layerage. </param> /// <returns> The render image. </returns> public static ICanvasImage Render(ICanvasResourceCreator resourceCreator, IList <Layerage> layerages) { ICanvasImage previousImage = null; for (int i = layerages.Count - 1; i >= 0; i--) { Layerage currentLayerage = layerages[i]; ILayer currentLayer = currentLayerage.Self; if (currentLayer.Visibility == Visibility.Collapsed) { continue; } if (currentLayer.Opacity == 0) { continue; } //Layer ICanvasImage currentImage = currentLayer.GetActualRender(resourceCreator, currentLayerage.Children); if (currentImage == null) { continue; } if (previousImage == null) { previousImage = currentImage; continue; } //Blend if (currentLayer.BlendMode is BlendEffectMode blendMode) { previousImage = new BlendEffect { Background = currentImage, Foreground = previousImage, Mode = blendMode }; continue; } //Composite previousImage = new CompositeEffect { Sources = { previousImage, currentImage, } }; continue; } return(previousImage); }
public BlendEffectProcessor(IImageProvider source) { SetDefaultParameters(); m_blendEffect = new BlendEffect(); // SetupEffectCategory(m_blendEffect); m_blendEffect.Source = source; AddEditors(); }
private void DrawFrame(CanvasDrawingSession ds) { //ds.Clear(); if (_background != null) { var tile = new TileEffect(); tile.Source = _background; tile.SourceRectangle = new Rect(0, 0, 400, 400); ds.DrawImage(tile); } using (var blendDs = _buffer.CreateDrawingSession()) { blendDs.Clear(); } foreach (var layer in _layers.Reverse().Where(l => l.IsVisible)) { using (var tmpDs = _tmpBuffer.CreateDrawingSession()) { tmpDs.Clear(Colors.Transparent); switch (layer.BlendMode) { case BlendMode.Normal: tmpDs.DrawImage(_buffer); tmpDs.DrawImage(layer.Image, (float)layer.Opacity / 100); break; case BlendMode.Addition: tmpDs.DrawImage(_buffer); tmpDs.Blend = CanvasBlend.Add; tmpDs.DrawImage(layer.Image, (float)layer.Opacity / 100); break; default: using (var alpha = layer.Image.Clone()) using (var blend = new BlendEffect()) { using (var alphaDs = alpha.CreateDrawingSession()) { alphaDs.DrawImage(layer.Image, (float)layer.Opacity / 100); } blend.Background = _buffer; blend.Foreground = alpha; blend.Mode = layer.BlendMode.ToBlendEffectMode(); tmpDs.DrawImage(blend); } break; } } using (var blendDs = _buffer.CreateDrawingSession()) { blendDs.Clear(); blendDs.DrawImage(_tmpBuffer); } ds.DrawImage(_buffer); } }
protected override void OnConnected() { Compositor compositor = Window.Current.Compositor; // CompositionCapabilities: Are Effects supported? bool usingFallback = !CompositionCapabilities.GetForCurrentView().AreEffectsSupported(); if (usingFallback) { // If Effects are not supported, use Fallback Solid Color CompositionBrush = compositor.CreateColorBrush(FallbackColor); return; } // Define Effect graph var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.LinearBurn, Background = new ColorSourceEffect() { Name = "Tint", Color = Windows.UI.Colors.Silver, }, Foreground = new GaussianBlurEffect() { Name = "Blur", Source = new CompositionEffectSourceParameter("Backdrop"), BlurAmount = 0, BorderMode = EffectBorderMode.Hard, } }; // Create EffectFactory and EffectBrush CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount" }); CompositionEffectBrush effectBrush = effectFactory.CreateBrush(); // Create BackdropBrush CompositionBackdropBrush backdrop = compositor.CreateBackdropBrush(); effectBrush.SetSourceParameter("backdrop", backdrop); // Trivial looping animation to demonstrate animated effects TimeSpan _duration = TimeSpan.FromSeconds(5); ScalarKeyFrameAnimation blurAnimation = compositor.CreateScalarKeyFrameAnimation(); blurAnimation.InsertKeyFrame(0, 0); blurAnimation.InsertKeyFrame(0.5f, 10f); blurAnimation.InsertKeyFrame(1, 0); blurAnimation.IterationBehavior = AnimationIterationBehavior.Forever; blurAnimation.Duration = _duration; effectBrush.Properties.StartAnimation("Blur.BlurAmount", blurAnimation); // Set EffectBrush to paint Xaml UIElement CompositionBrush = effectBrush; }
public void LinkLayerEffects(Layer nextLayer) { IGraphicsEffect source = _inputEffect; _chainedEffect = null; // Link the effect chain foreach (var effect in Effects) { if (effect.Enabled) { effect.GraphicsEffect.GetType().GetProperties().FirstOrDefault(x => x.Name == "Source").SetValue(effect.GraphicsEffect, source); source = effect.GraphicsEffect; _chainedEffect = effect.GraphicsEffect; } } if (nextLayer != null) { IGraphicsEffect layerEffect = EffectRoot; IGraphicsEffect blendEffect; blendEffect = Helpers.GetEffectFromBlendMode(_blendMode); if (blendEffect is BlendEffect) { BlendEffect blend = (BlendEffect)blendEffect; blend.Foreground = nextLayer.GenerateEffectGraph(false); blend.Background = layerEffect; _blendEffect = blend; } else if (blendEffect is CompositeEffect) { CompositeEffect composite = (CompositeEffect)blendEffect; composite.Sources.Add(nextLayer.GenerateEffectGraph(false)); composite.Sources.Add(layerEffect); _blendEffect = composite; } else if (blendEffect is ArithmeticCompositeEffect) { ArithmeticCompositeEffect arith = (ArithmeticCompositeEffect)blendEffect; arith.Source1 = layerEffect; arith.Source2 = nextLayer.GenerateEffectGraph(false); _blendEffect = arith; } else { Debug.Assert(false); } } else { _blendEffect = null; } }
public static ICanvasImage RenderTransform(Layer l, ICanvasImage ci) { if (l.Visual == true && l.Opacity != 0) //图层可视且透明度大于零 { if (l.Opacity == 100) //无透明度渲染 { //图层无混合模式 if (l.BlendIndex == 0) { ci = new CompositeEffect { Sources = { ci, GetTransform(l.CanvasRenderTarget, l.Vect) } } } ; //结合接口 //图层有混合模式 else { ci = new BlendEffect() { Background = GetTransform(l.CanvasRenderTarget, l.Vect), Foreground = ci, Mode = l.BlendMode, } }; //混合接口 } else if (l.Opacity == 0) //透明度渲染 { return(ci); } else// if (l.Opacity < 100)//有透明度渲染 { ICanvasImage oci = new OpacityEffect { Source = GetTransform(l.CanvasRenderTarget, l.Vect), Opacity = (float)(l.Opacity / 100) }; //透明度接口 //图层无混合模式 if (l.BlendIndex == 0) { ci = new CompositeEffect { Sources = { ci, oci } } } ; //结合接口 //图层有混合模式 else { ci = new BlendEffect() { Background = oci, Foreground = ci, Mode = l.BlendMode, } }; //混合接口 } } return(ci); }
/// <summary> /// Constructs a high pass effect with the specified parameters. /// </summary> /// <param name="kernelSize">The size of the filter kernel. A larger size preserves more of lower frequencies.</param> /// <param name="isGrayscale">True if the highpass effect should give a grayscale result. Otherwise the individual R, G, B channels are treated separately.</param> /// <param name="downscaleDivisor">How much to downscale the image to reduce the cost of the internal blur operation, trading speed for some fidelity. Suitable value depends on the kernelSize.</param> public HighpassEffect(uint kernelSize, bool isGrayscale = false, uint downscaleDivisor = 1) { m_kernelSize = kernelSize; m_downscaleDivisor = downscaleDivisor; m_isGrayscale = isGrayscale; if (m_downscaleDivisor > 1) { m_downscaleFilterEffect = new FilterEffect(/*source*/) { Filters = new IFilter[] { new ScaleFilter(1.0 / m_downscaleDivisor) } }; m_downscaleCachingEffect = new CachingEffect(m_downscaleFilterEffect); int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize / m_downscaleDivisor)); m_blurFilter = new BlurFilter(blurKernelSize); m_blurredFilterEffect = new FilterEffect(m_downscaleCachingEffect) { Filters = new IFilter[] { m_blurFilter } }; m_highPassBlendEffect = new BlendEffect(/*source*/) { ForegroundSource = m_blurredFilterEffect, BlendFunction = BlendFunction.SignedDifference }; } else { int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize)); m_blurFilter = new BlurFilter(blurKernelSize); m_blurredFilterEffect = new FilterEffect(/*source*/) { Filters = new IFilter[] { m_blurFilter } }; m_highPassBlendEffect = new BlendEffect(/*source*/) { ForegroundSource = m_blurredFilterEffect, BlendFunction = BlendFunction.SignedDifference }; } if (m_isGrayscale) { m_highPassGrayscaleFilterEffect = new FilterEffect(m_highPassBlendEffect) { Filters = new IFilter[] { new GrayscaleFilter() } }; } }
public static CompositionBrush BuildMicaEffectBrush(Compositor compositor, Color tintColor, float tintOpacity, float luminosityOpacity) { // Tint Color. var tintColorEffect = new ColorSourceEffect(); tintColorEffect.Name = "TintColor"; tintColorEffect.Color = tintColor; // OpacityEffect applied to Tint. var tintOpacityEffect = new OpacityEffect(); tintOpacityEffect.Name = "TintOpacity"; tintOpacityEffect.Opacity = tintOpacity; tintOpacityEffect.Source = tintColorEffect; // Apply Luminosity: // Luminosity Color. var luminosityColorEffect = new ColorSourceEffect(); luminosityColorEffect.Color = tintColor; // OpacityEffect applied to Luminosity. var luminosityOpacityEffect = new OpacityEffect(); luminosityOpacityEffect.Name = "LuminosityOpacity"; luminosityOpacityEffect.Opacity = luminosityOpacity; luminosityOpacityEffect.Source = luminosityColorEffect; // Luminosity Blend. var luminosityBlendEffect = new BlendEffect(); luminosityBlendEffect.Mode = BlendEffectMode.Color; luminosityBlendEffect.Background = new CompositionEffectSourceParameter("BlurredWallpaperBackdrop"); luminosityBlendEffect.Foreground = luminosityOpacityEffect; // Apply Tint: // Color Blend. var colorBlendEffect = new BlendEffect(); colorBlendEffect.Mode = BlendEffectMode.Luminosity; colorBlendEffect.Background = luminosityBlendEffect; colorBlendEffect.Foreground = tintOpacityEffect; CompositionEffectBrush micaEffectBrush = compositor.CreateEffectFactory(colorBlendEffect).CreateBrush(); var blurredWallpaperBackdropBrush = (ICompositorWithBlurredWallpaperBackdropBrush)((object)compositor); micaEffectBrush.SetSourceParameter("BlurredWallpaperBackdrop", blurredWallpaperBackdropBrush.TryCreateBlurredWallpaperBackdropBrush()); return(micaEffectBrush); }
public void CreatesBlendEffectBlendingWithSelfGraph() { var bitmap = new Bitmap(new Size(10, 10), ColorMode.Argb8888); using (var source = new BitmapImageSource(bitmap)) using (var blendEffect = new BlendEffect(source, source)) { string result = CreateGraph(blendEffect); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(source))).Matches(result).Count); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(blendEffect))).Matches(result).Count); } }
/// <summary> /// Creates a custom shaped Effect Brush using BackdropBrush and a Mask /// </summary> /// <param name="compositor">Compositor</param> /// <param name="mask">IMaskSurface</param> /// <param name="blendColor">Color to blend in the BackdropBrush</param> /// <param name="blurAmount">Blur Amount of the Backdrop Brush</param> /// <param name="backdropBrush">Backdrop Brush (optional). If not provided, then compositor creates it.</param> /// <returns>CompositionEffectBrush</returns> public static CompositionEffectBrush CreateMaskedBackdropBrush(this Compositor compositor, IMaskSurface mask, Color blendColor, float blurAmount, CompositionBackdropBrush backdropBrush = null) { // Blur Effect var blurEffect = new GaussianBlurEffect() { Name = "Blur", BlurAmount = blurAmount, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("backdrop"), }; // Blend Effect var blendEffect = new BlendEffect { Foreground = new ColorSourceEffect { Name = "Color", Color = blendColor }, Background = blurEffect, Mode = BlendEffectMode.Multiply }; // Composite Effect var effect = new CompositeEffect { Mode = CanvasComposite.DestinationIn, Sources = { blendEffect, new CompositionEffectSourceParameter("mask") } }; // Create Effect Factory var factory = compositor.CreateEffectFactory(effect, new[] { "Blur.BlurAmount", "Color.Color" }); // Create Effect Brush var brush = factory.CreateBrush(); // Set the BackDropBrush // If no backdrop brush is provided, create one brush.SetSourceParameter("backdrop", backdropBrush ?? compositor.CreateBackdropBrush()); // Set the Mask // Create SurfaceBrush from IMaskSurface var maskBrush = compositor.CreateSurfaceBrush(mask.Surface); brush.SetSourceParameter("mask", maskBrush); return(brush); }
private static async Task CreateImageEffectAsync(AppServiceRequestReceivedEventArgs message, BackgroundTaskDeferral wholeTaskDeferral) { try { var messageDef = message.GetDeferral(); try { var targetFileToken = message.Request.Message["targetFileToken"].ToString(); var targetFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(targetFileToken); var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Guid.NewGuid().ToString("N") + ".jpg"); var foregroundImage = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Paillete.png")); //use the blureffect using (var inputStream = await targetFile.OpenReadAsync()) using (var foregroundImageStream = await foregroundImage.OpenReadAsync()) { var effect = new BlendEffect(new RandomAccessStreamImageSource(inputStream), new RandomAccessStreamImageSource(foregroundImageStream)); inputStream.Seek(0); foregroundImageStream.Seek(0); //effect.Source = new RandomAccessStreamImageSource(inputStream); //effect.BlendFunction = BlendFunction.Add; //effect.ForegroundSource = new RandomAccessStreamImageSource(foregroundImageStream); using (var jpegRenderer = new JpegRenderer(effect)) using (var stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { // Jpeg renderer gives the raw buffer that contains the filtered image. IBuffer jpegBuffer = await jpegRenderer.RenderAsync(); await stream.WriteAsync(jpegBuffer); await stream.FlushAsync(); } } var outputFileToken = SharedStorageAccessManager.AddFile(outputFile); await message.Request.SendResponseAsync(new ValueSet { { "outputFileToken", outputFileToken } }); } finally { // fermeture du message messageDef.Complete(); } } finally { // On ne fera pas d'autres communications wholeTaskDeferral.Complete(); } }
void InitializeBloomFilter() { BloomEnabled = true; // A bloom filter makes graphics appear to be bright and glowing by adding blur around only // the brightest parts of the image. This approximates the look of HDR (high dynamic range) // rendering, in which the color of the brightest light sources spills over onto surrounding // pixels. // // Many different visual styles can be achieved by adjusting these settings: // // Intensity = how much bloom is added // 0 = none // // Threshold = how bright does a pixel have to be in order for it to bloom // 0 = the entire image blooms equally // // Blur = how much the glow spreads sideways around bright areas BloomIntensity = 200; BloomThreshold = 80; BloomBlur = 48; // Before drawing, properties of these effects will be adjusted to match the // current settings (see ApplyBloomFilter), and an input image connected to // extractBrightAreas.Source and bloomResult.Background (see DemandCreateBloomRenderTarget). // Step 1: use a transfer effect to extract only pixels brighter than the threshold. extractBrightAreas = new LinearTransferEffect { ClampOutput = true, }; // Step 2: blur these bright pixels. blurBrightAreas = new GaussianBlurEffect { Source = extractBrightAreas, }; // Step 3: adjust how much bloom is wanted. adjustBloomIntensity = new LinearTransferEffect { Source = blurBrightAreas, }; // Step 4: blend the bloom over the top of the original image. bloomResult = new BlendEffect { Foreground = adjustBloomIntensity, Mode = BlendEffectMode.Screen, }; }
private void BlendTileToCanvas(Point blendPosition) { var blendEffect = new BlendEffect(); m_disposables.Add(blendEffect); blendEffect.Source = m_imageProvider; blendEffect.ForegroundSource = m_tileSource; blendEffect.TargetArea = new Rect(blendPosition, m_relativeTileSize); blendEffect.TargetOutputOption = OutputOption.Stretch; m_imageProvider = blendEffect; }
public void TintedBrush() { // Create the graphics effect var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.Multiply, Background = new CompositionEffectSourceParameter("image"), Foreground = new ColorSourceEffect { Name = "colorSource", Color = Color.FromArgb(255, 255, 255, 255) } }; // Compile the effect, specifying that the color should be modifiable. var effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "colorSource.Color" }); // Load our image CompositionSurfaceBrush surfaceBrush = _compositor.CreateSurfaceBrush(); LoadImage(surfaceBrush, new Uri("ms-appx:///Assets/cat.png")); // Create a visual with an instance of the effect that tints in red var redEffect = effectFactory.CreateBrush(); // Set parameters for image, which is not animatable redEffect.SetSourceParameter("image", surfaceBrush); // Set properties for color, which is animatable redEffect.Properties.InsertColor("colorSource.Color", Colors.Red); var redVisual = _compositor.CreateSpriteVisual(); redVisual.Brush = redEffect; redVisual.Size = new Vector2(219, 300); _root.Children.InsertAtBottom(redVisual); // Create a visual with an instance of the effect that tints in blue var blueEffect = effectFactory.CreateBrush(); blueEffect.SetSourceParameter("image", surfaceBrush); blueEffect.Properties.InsertColor("colorSource.Color", Colors.Blue); var blueVisual = _compositor.CreateSpriteVisual(); blueVisual.Brush = blueEffect; blueVisual.Offset = new Vector3(400, 0, 0); blueVisual.Size = new Vector2(219, 300); _root.Children.InsertAtBottom(blueVisual); }
/// <summary> /// Constructs a high pass effect with the specified parameters. /// </summary> /// <param name="kernelSize">The size of the filter kernel. A larger size preserves more of lower frequencies.</param> /// <param name="isGrayscale">True if the highpass effect should give a grayscale result. Otherwise the individual R, G, B channels are treated separately.</param> /// <param name="downscaleDivisor">How much to downscale the image to reduce the cost of the internal blur operation, trading speed for some fidelity. Suitable value depends on the kernelSize.</param> public HighpassEffect(uint kernelSize, bool isGrayscale = false, uint downscaleDivisor = 1) { m_kernelSize = kernelSize; m_downscaleDivisor = downscaleDivisor; m_isGrayscale = isGrayscale; if (m_downscaleDivisor > 1) { m_downscaleFilterEffect = new FilterEffect(/*source*/) { Filters = new IFilter[] { new ScaleFilter(1.0 / m_downscaleDivisor) } }; m_downscaleCachingEffect = new CachingEffect(m_downscaleFilterEffect); int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize / m_downscaleDivisor)); m_blurFilter = new BlurFilter(blurKernelSize); m_blurredFilterEffect = new FilterEffect(m_downscaleCachingEffect) { Filters = new IFilter[] { m_blurFilter } }; m_highPassBlendEffect = new BlendEffect( /*source*/) { ForegroundSource = m_blurredFilterEffect, BlendFunction = BlendFunction.SignedDifference }; } else { int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize)); m_blurFilter = new BlurFilter(blurKernelSize); m_blurredFilterEffect = new FilterEffect(/*source*/) { Filters = new IFilter[] { m_blurFilter } }; m_highPassBlendEffect = new BlendEffect( /*source*/) { ForegroundSource = m_blurredFilterEffect, BlendFunction = BlendFunction.SignedDifference }; } if (m_isGrayscale) { m_highPassGrayscaleFilterEffect = new FilterEffect(m_highPassBlendEffect) { Filters = new IFilter[] { new GrayscaleFilter() } }; } }
public async Task RenderHighpassEffectGroupAndAmplifyEdges() { using (var source = KnownImages.MikikoLynn.ImageSource) using (var highpassEffect = new HighpassEffectGroup(14, true, 2) { Source = source }) using (var sourceWithAmplifiedEdges = new BlendEffect(source, highpassEffect, BlendFunction.Hardlight, 0.4)) using (var renderer = new JpegRenderer(sourceWithAmplifiedEdges)) { DiagnosticsReport.BeginProbe(sourceWithAmplifiedEdges); var buffer = await renderer.RenderAsync(); // This should hit the inline blending (fast) path, make sure it did. var blendEffectReport = await DiagnosticsReport.EndProbeAsync(sourceWithAmplifiedEdges); Assert.AreEqual(1, (int)blendEffectReport.Properties["inlineblend_count"]); ImageResults.Instance.SaveToPicturesLibrary(buffer); } }
private void SetupBlur() { compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; var blur = new GaussianBlurEffect { Name = "Blur", Source = new CompositionEffectSourceParameter("Backdrop"), BlurAmount = 0.0f, BorderMode = EffectBorderMode.Hard }; var blend = new BlendEffect { Name = "Blend", Foreground = new ColorSourceEffect { Color = Color.FromArgb(128, 30, 30, 220), Name = "ColorSource" }, Background = blur, Mode = BlendEffectMode.Overlay }; var effectFactory = compositor.CreateEffectFactory(blend, new[] {"Blur.BlurAmount"}); brush = effectFactory.CreateBrush(); var backdrop = compositor.CreateBackdropBrush(); brush.SetSourceParameter("Backdrop", backdrop); var sprite = compositor.CreateSpriteVisual(); sprite.Brush = brush; sprite.Size = new Vector2((float) TargetImage.ActualWidth, (float) TargetImage.ActualHeight); ElementCompositionPreview.SetElementChildVisual(TargetImage, sprite); }
protected override async void Render() { try { if (Source != null) { Debug.WriteLine(DebugTag + Name + ": Rendering..."); foreach (var change in Changes) { change(); } Changes.Clear(); //blend source layer with mode overlay var blendEffect = new BlendEffect(); blendEffect.Source = Source;// new StreamImageSource(new MemoryStream()); blendEffect.ForegroundSource = Source; blendEffect.BlendFunction = BlendFunction.Overlay; blendEffect.GlobalAlpha = 0.0; var renderer = new JpegRenderer(blendEffect); var outBuffer = await renderer.RenderAsync(); blendEffect.Dispose(); var highPassSource = new BufferImageSource(outBuffer); var highPassFilter = new HighpassEffect(6, false, 1); highPassFilter.Source = highPassSource; var highPassRenderer = new JpegRenderer(highPassFilter); var highPassOutBuffer = await highPassRenderer.RenderAsync(); highPassFilter.Dispose(); var negativeFilter = new NegativeFilter(); var filterEffect = new FilterEffect(); filterEffect.Filters = new List<IFilter>() { negativeFilter }; filterEffect.Source = new BufferImageSource(highPassOutBuffer); var invertRenderer = new JpegRenderer(filterEffect); var invertOutBuffer = await invertRenderer.RenderAsync(); blendEffect = new BlendEffect(Source, new BufferImageSource(invertOutBuffer), BlendFunction.Overlay, 0.5); using (var bmpRender = new WriteableBitmapRenderer(blendEffect, TmpBitmap)) { await bmpRender.RenderAsync(); } TmpBitmap.Pixels.CopyTo(PreviewBitmap.Pixels, 0); PreviewBitmap.Invalidate(); // Force a redraw } else { Debug.WriteLine(DebugTag + Name + ": Render(): No buffer set!"); } } catch (Exception e) { Debug.WriteLine(DebugTag + Name + ": Render(): " + e.Message); } finally { switch (State) { case States.Apply: State = States.Wait; break; case States.Schedule: State = States.Apply; Render(); break; default: break; } } }
private void Initialize() { _cameraPreviewImageSource = new CameraPreviewImageSource(_photoCaptureDevice); if (_blendImageUri != null) { _blendImageProvider = new StreamImageSource((System.Windows.Application.GetResourceStream(_blendImageUri).Stream)); } else { var colorStops = new GradientStop[] { new GradientStop { Color = Color.FromArgb(0xFF, 0xFF, 0x00, 0x00), Offset = 0.0 }, new GradientStop { Color = Color.FromArgb(0xFF, 0x00, 0xFF, 0x00), Offset = 0.7 }, new GradientStop { Color = Color.FromArgb(0xFF, 0x00, 0x00, 0xFF), Offset = 1.0 } }; var gradient = new RadialGradient(new Point(0, 0), new EllipseRadius(1, 0), colorStops); var size = new Size(640, 480); _blendImageProvider = new GradientImageSource(size, gradient); } var nameFormat = "{0}/" + EffectCount + " - {1}"; switch (_effectIndex) { case 0: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_None); } break; case 1: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Normal); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Normal, GlobalAlpha); } break; case 2: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Multiply); _blendEffect = new BlendEffect(_cameraPreviewImageSource, _blendImageProvider, BlendFunction.Multiply, GlobalAlpha); } break; case 3: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Add); _blendEffect = new BlendEffect(_cameraPreviewImageSource, _blendImageProvider, BlendFunction.Add, GlobalAlpha); } break; case 4: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Color); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Color, GlobalAlpha); } break; case 5: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Colorburn); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Colorburn, GlobalAlpha); } break; case 6: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Colordodge); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Colordodge, GlobalAlpha); } break; case 7: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Overlay); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Overlay, GlobalAlpha); } break; case 8: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Softlight); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Softlight, GlobalAlpha); } break; case 9: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Screen); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Screen, GlobalAlpha); } break; case 10: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Hardlight); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Hardlight, GlobalAlpha); } break; case 11: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Darken); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Darken, GlobalAlpha); } break; case 12: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Lighten); _blendEffect = new BlendEffect(_cameraPreviewImageSource, _blendImageProvider, BlendFunction.Lighten, GlobalAlpha); } break; case 13: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Hue); _blendEffect = new BlendEffect(_cameraPreviewImageSource, _blendImageProvider, BlendFunction.Hue, GlobalAlpha); } break; case 14: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Exclusion); _blendEffect = new BlendEffect(_cameraPreviewImageSource, _blendImageProvider, BlendFunction.Exclusion, GlobalAlpha); } break; case 15: { EffectName = String.Format(nameFormat, _effectIndex + 1, AppResources.Filter_Blend_Difference); _blendEffect = new BlendEffect(_cameraPreviewImageSource,_blendImageProvider, BlendFunction.Difference, GlobalAlpha); } break; } if (_blendEffect != null) { _blendEffect.TargetArea = _targetArea; _blendEffect.TargetAreaRotation = _targetAreaRotation; } }
private void BlendTileToCanvas(Point blendPosition) { var blendEffect = new BlendEffect(); m_disposables.Add(blendEffect); blendEffect.Source = m_imageProvider; blendEffect.ForegroundSource = m_tileSource; blendEffect.TargetArea = new Rect(blendPosition, m_relativeTileSize); blendEffect.TargetOutputOption = OutputOption.Stretch; m_imageProvider = blendEffect; }
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(); } } }
private ICanvasImage CreateBlend() { var rotatedTiger = new Transform3DEffect { Source = bitmapTiger }; var blendEffect = new BlendEffect { Background = bitmapTiger, Foreground = rotatedTiger }; // Animation swings the second copy of the image back and forth, // while cycling through the different blend modes. int enumValueCount = Utils.GetEnumAsList<BlendEffectMode>().Count; animationFunction = elapsedTime => { blendEffect.Mode = (BlendEffectMode)(elapsedTime / Math.PI % enumValueCount); textLabel = "Mode: " + blendEffect.Mode; rotatedTiger.TransformMatrix = Matrix4x4.CreateRotationZ((float)Math.Sin(elapsedTime)); }; return blendEffect; }
public static IImageProvider Generate(IImageProvider objectMaskSource, LinearGradient gradient, Size size, IReadOnlyList<ILensBlurKernel> kernels) { var backgroundSource = new GradientImageSource(size, gradient); var blendEffect = new BlendEffect(backgroundSource, objectMaskSource, BlendFunction.Lighten); return new IndexRemappingEffect(blendEffect, kernels.Count + 2); }
public void CreatesBlendEffectBlendingWithSelfGraph() { var bitmap = new Bitmap(new Size(10, 10), ColorMode.Argb8888); using (var source = new BitmapImageSource(bitmap)) using (var blendEffect = new BlendEffect(source, source)) { string result = CreateGraph(blendEffect); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(source))).Matches(result).Count); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(blendEffect))).Matches(result).Count); } }
private CompositionEffectBrush CreateBlurBrush() { var blurEffect = new GaussianBlurEffect() { Name = "BlurEffect", BlurAmount = (float)BlurAmount, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("Source"), BorderMode = EffectBorderMode.Hard }; var colorEffect = new ColorSourceEffect() { Name = "ColorEffect", Color = TintColor }; var blendEffect = new BlendEffect() { Background = blurEffect, Foreground = colorEffect, Mode = BlendEffectMode.SoftLight }; var effectFactory = _compositor.CreateEffectFactory(blendEffect, new[] { "BlurEffect.BlurAmount", "ColorEffect.Color" }); return effectFactory.CreateBrush(); }
public void TintedBrush() { // Create the graphics effect var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.Multiply, Background = new CompositionEffectSourceParameter("image"), Foreground = new ColorSourceEffect { Name = "colorSource", Color = Color.FromArgb(255, 255, 255, 255) } }; // Compile the effect, specifying that the color should be modifiable. var effectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "colorSource.Color" }); // Load our image CompositionSurfaceBrush surfaceBrush = _compositor.CreateSurfaceBrush(); LoadImage(surfaceBrush, new Uri("ms-appx:///Assets/cat.png")); // Create a visual with an instance of the effect that tints in red var redEffect = effectFactory.CreateBrush(); // Set parameters for image, which is not animatable redEffect.SetSourceParameter("image", surfaceBrush); // Set properties for color, which is animatable redEffect.Properties.InsertColor("colorSource.Color", Colors.Red); var redVisual = _compositor.CreateSpriteVisual(); redVisual.Brush = redEffect; redVisual.Size = new Vector2(219, 300); _root.Children.InsertAtBottom(redVisual); // Create a visual with an instance of the effect that tints in blue var blueEffect = effectFactory.CreateBrush(); blueEffect.SetSourceParameter("image", surfaceBrush); blueEffect.Properties.InsertColor("colorSource.Color", Colors.Blue); var blueVisual = _compositor.CreateSpriteVisual(); blueVisual.Brush = blueEffect; blueVisual.Offset = new Vector3(400, 0, 0); blueVisual.Size = new Vector2(219, 300); _root.Children.InsertAtBottom(blueVisual); }
private void CreateTextAndBlendEffect(Vector2 sizeLightBounds) { // // Crete the effect graph, doing a hard light blend of the text over the // content already drawn into the backbuffer // IGraphicsEffect graphicsEffect = new BlendEffect() { Mode = BlendEffectMode.HardLight, Foreground = new CompositionEffectSourceParameter("Text"), Background = new CompositionEffectSourceParameter("Destination"), }; CompositionEffectFactory effectFactory = _compositor.CreateEffectFactory(graphicsEffect, null); CompositionEffectBrush brush = effectFactory.CreateBrush(); // Bind the destination brush brush.SetSourceParameter("Destination", _compositor.CreateBackdropBrush()); // // Create the text surface which we'll scroll over the image with the lighting effect // // Pick a nice size font depending on target size const float maxFontSize = 72; const float scaleFactor = 12; float fontSize = Math.Min(sizeLightBounds.X / scaleFactor, maxFontSize); // Create the text format description, then the surface CanvasTextFormat textFormat = new CanvasTextFormat { FontFamily = "Segoe UI", FontSize = fontSize, FontWeight = FontWeights.Bold, WordWrapping = CanvasWordWrapping.WholeWord, HorizontalAlignment = CanvasHorizontalAlignment.Center, VerticalAlignment = CanvasVerticalAlignment.Center }; string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec efficitur, eros sit amet laoreet scelerisque, " + "nunc odio ultricies metus, ut consectetur nulla massa eu nibh.Phasellus in lorem id nunc euismod tempus.Phasellus et nulla non turpis tempor blandit ut eget turpis." + "Phasellus ac ornare elit, ut scelerisque dolor. Nam vel finibus lorem. Aenean malesuada pulvinar eros id ornare. Fusce blandit ante eget dolor efficitur suscipit." + "Phasellus ac lacus nibh. Aenean eget blandit risus, in lacinia mi. Proin fermentum ante eros, non sollicitudin mi pretium eu. Curabitur suscipit lectus arcu, eget" + "pretium quam sagittis non. Mauris purus mauris, condimentum nec laoreet sit amet, imperdiet sit amet nisi. Sed interdum, urna et aliquam porta, elit velit tincidunt orci," + "vitae vestibulum risus lacus at nulla.Phasellus sapien ipsum, pellentesque varius enim nec, iaculis aliquet enim. Nulla id dapibus ante. Sed hendrerit sagittis leo, commodo" + "fringilla ligula rutrum ut. Nullam sodales, ex ut pellentesque scelerisque, sapien nulla mattis lectus, vel ullamcorper leo enim ac mi.Sed consectetur vitae velit in consequat." + "Pellentesque ac condimentum justo, at feugiat nulla. Sed ut congue neque. Nam gravida quam ac urna porttitor, ut bibendum ante mattis.Cras viverra cursus sapien, et sollicitudin" + "risus fringilla eget. Nulla facilisi. Duis pellentesque scelerisque nisi, facilisis malesuada massa gravida et. Vestibulum ac leo sed orci tincidunt feugiat.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc id leo vestibulum, vulputate ipsum sit amet, scelerisque velit. Curabitur imperdiet justo et tortor dignissim, sit amet volutpat sem ullamcorper. Nam mollis ullamcorper tellus vitae convallis. Aliquam eleifend elit nec tincidunt pharetra. Aliquam turpis eros, mollis et nunc quis, porta molestie justo. Etiam ultrices sem non turpis imperdiet dictum.Aliquam molestie elit in urna sodales, nec luctus dui laoreet.Curabitur molestie risus vel ligula efficitur, non fringilla urna iaculis.Curabitur neque tortor, facilisis quis dictum facilisis, facilisis et ante. Sed nisl erat, semper vitae efficitur ut, congue vitae quam. Ut auctor lacus sit amet varius placerat.Sed ac tellus tempus, ultricies est quis, tempor felis.Nulla vel faucibus elit, eu tincidunt eros. Nulla blandit id nisl ut porta. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam suscipit tellus a mattis pulvinar. Sed et libero vel ligula elementum suscipit.Ut elementum libero at sagittis pharetra. Fusce ultrices odio sapien, a posuere est consectetur ut."; // Make the surface twice the height to give us room to scroll Vector2 surfaceSize = new Vector2(sizeLightBounds.X, 2f * sizeLightBounds.Y); CompositionDrawingSurface textSurface = SurfaceLoader.LoadText(text, surfaceSize.ToSize(), textFormat, Colors.White, Colors.Transparent); brush.SetSourceParameter("Text", _compositor.CreateSurfaceBrush(textSurface)); // Create the sprite and parent it to the panel with the clip _textSprite = _compositor.CreateSpriteVisual(); _textSprite.Size = surfaceSize; _textSprite.Brush = brush; ElementCompositionPreview.SetElementChildVisual(MyPanel, _textSprite); // Lastly, setup the slow scrolling animation of the text LinearEasingFunction linear = _compositor.CreateLinearEasingFunction(); Vector3KeyFrameAnimation offsetAnimation = _compositor.CreateVector3KeyFrameAnimation(); offsetAnimation.InsertKeyFrame(0f, new Vector3(0, 0, 0), linear); offsetAnimation.InsertKeyFrame(1f, new Vector3(0, -_textSprite.Size.Y * .5f, 0), linear); offsetAnimation.Duration = TimeSpan.FromMilliseconds(30000); offsetAnimation.IterationBehavior = AnimationIterationBehavior.Forever; _textSprite.StartAnimation("Offset", offsetAnimation); }
private CompositionEffectBrush BuildBlurBrush() { GaussianBlurEffect blurEffect = new GaussianBlurEffect() { Name = "Blur", BlurAmount = 0.0f, BorderMode = EffectBorderMode.Hard, Optimization = EffectOptimization.Balanced, Source = new CompositionEffectSourceParameter("source"), }; BlendEffect blendEffect = new BlendEffect { Background = blurEffect, Foreground = new ColorSourceEffect { Name = "Color", Color = Color.FromArgb(64, 255, 255, 255) }, Mode = BlendEffectMode.SoftLight }; SaturationEffect saturationEffect = new SaturationEffect { Source = blendEffect, Saturation = 1.75f, }; BlendEffect finalEffect = new BlendEffect { Foreground = new CompositionEffectSourceParameter("NoiseImage"), Background = saturationEffect, Mode = BlendEffectMode.Screen, }; var factory = Compositor.CreateEffectFactory( finalEffect, new[] { "Blur.BlurAmount", "Color.Color" } ); CompositionEffectBrush brush = factory.CreateBrush(); brush.SetSourceParameter("NoiseImage", m_noiseBrush); return brush; }
private void SamplePage_Loaded(object sender, RoutedEventArgs e) { //get interop compositor _compositor = ElementCompositionPreview.GetElementVisual(MainGrid).Compositor; //get image brush and image visual _image = Image; _imageVisual = _image.SpriteVisual; _imageBrush = _image.SurfaceBrush; //load height map to surface brush _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _normalMapSurface = _imageLoader.CreateManagedSurfaceFromUri(new Uri("ms-appx:///Samples/SDK Insider/ImageLightingPlayground/rocks_NM_height.png")); _normalMapBrush = _compositor.CreateSurfaceBrush(); _normalMapBrush.Surface = _normalMapSurface.Surface; //set up lighting effects: // DISTANT DIFFUSE // Effect description var distantDiffuseDesc = new ArithmeticCompositeEffect { Source1 = new CompositionEffectSourceParameter("Image"), Source2 = new DistantDiffuseEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Source1Amount = 0, Source2Amount = 0, MultiplyAmount = 1 }; //Create (Light)EffectBrush from EffectFactory and specify animatable properties _distantDiffuseLightBrush = _compositor.CreateEffectFactory( distantDiffuseDesc, new[] { "light.Azimuth", "light.Elevation", "light.DiffuseAmount", "light.LightColor" } ).CreateBrush(); //set source parameters to image and normal map _distantDiffuseLightBrush.SetSourceParameter( "Image", _imageBrush); _distantDiffuseLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); // DISTANT SPECULAR // Effect description var distantSpecularDesc = new BlendEffect { Foreground = new CompositionEffectSourceParameter("Image"), Background = new DistantSpecularEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Mode = BlendEffectMode.Screen }; //Create (Light)EffectBrush from EffectFactory and specify animatable properties _distantSpecularLightBrush = _compositor.CreateEffectFactory( distantSpecularDesc, new[] { "light.Azimuth", "light.Elevation", "light.SpecularExponent", "light.SpecularAmount", "light.LightColor" } ).CreateBrush(); //set source parameters to image and normal map _distantSpecularLightBrush.SetSourceParameter( "Image", _imageBrush); _distantSpecularLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); // POINT DIFFUSE // Effect description var pointDiffuseDesc = new ArithmeticCompositeEffect { Source1 = new CompositionEffectSourceParameter("Image"), Source2 = new PointDiffuseEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Source1Amount = 0, Source2Amount = 0, MultiplyAmount = 1 }; //Create (Light)EffectBrush from EffectFactory and specify animatable properties _pointDiffuseLightBrush = _compositor.CreateEffectFactory( pointDiffuseDesc, new[] { "light.LightPosition", "light.DiffuseAmount", "light.HeightMapScale", "light.LightColor" } ).CreateBrush(); // set source parameters to image and normal map _pointDiffuseLightBrush.SetSourceParameter( "Image", _imageBrush); _pointDiffuseLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); // POINT SPECUALR // Effect description var pointSpecularDesc = new BlendEffect { Foreground = new CompositionEffectSourceParameter("Image"), Background = new PointSpecularEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Mode = BlendEffectMode.Screen }; //Create (Light)EffectBrush from EffectFactory and specify animatable properties _pointSpecularLightBrush = _compositor.CreateEffectFactory( pointSpecularDesc, new[] { "light.LightPosition", "light.SpecularExponent", "light.SpecularAmount", "light.HeightMapScale", "light.LightColor" } ).CreateBrush(); // set source parameters to image and normal map _pointSpecularLightBrush.SetSourceParameter( "Image", _imageBrush); _pointSpecularLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); //SPOT DIFFUSE // Effect description var spotDiffuseDesc = new ArithmeticCompositeEffect { Source1 = new CompositionEffectSourceParameter("Image"), Source2 = new SpotDiffuseEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Source1Amount = 0, Source2Amount = 0, MultiplyAmount = 1 }; //Create (Light)EffectBrush from EffectFactory and specify animatable properties _spotDiffuseLightBrush = _compositor.CreateEffectFactory( spotDiffuseDesc, new[] { "light.LightPosition", "light.LightTarget", "light.Focus", "light.LimitingConeAngle", "light.DiffuseAmount", "light.HeightMapScale", "light.LightColor" } ).CreateBrush(); // set source parameters to image and normal map _spotDiffuseLightBrush.SetSourceParameter( "Image", _imageBrush); _spotDiffuseLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); // SPOT SPECULAR // Effect description var spotSpecularDesc = new BlendEffect { Foreground = new CompositionEffectSourceParameter("Image"), Background = new SpotSpecularEffect { Name = "light", Source = new CompositionEffectSourceParameter("NormalMap") }, Mode = BlendEffectMode.Screen }; //Create (Light)EffectBrush from EffectFactory _spotSpecularLightBrush = _compositor.CreateEffectFactory( spotSpecularDesc, new[] { "light.LightPosition", "light.LightTarget", "light.Focus", "light.LimitingConeAngle", "light.SpecularExponent", "light.SpecularAmount", "light.HeightMapScale", "light.LightColor" } ).CreateBrush(); // set source parameters to image and normal map _spotSpecularLightBrush.SetSourceParameter( "Image", _imageBrush); _spotSpecularLightBrush.SetSourceParameter( "NormalMap", _normalMapBrush); // For simplying UI states switch, put light parameter grids in an array _lightParamsGrids = new Grid[(int)LightType.NumLightTypes]; _lightParamsGrids[(int)LightType.NoLight] = null; _lightParamsGrids[(int)LightType.DistantDiffuse] = DistantDiffuseParams; _lightParamsGrids[(int)LightType.DistantSpecular] = DistantSpecularParams; _lightParamsGrids[(int)LightType.PointDiffuse] = PointDiffuseParams; _lightParamsGrids[(int)LightType.PointSpecular] = PointSpecularParams; _lightParamsGrids[(int)LightType.SpotDiffuse] = SpotDiffuseParams; _lightParamsGrids[(int)LightType.SpotSpecular] = SpotSpecularParams; // Same as grids _lightBrushes = new CompositionBrush[(int)LightType.NumLightTypes]; _lightBrushes[(int)LightType.NoLight] = _imageBrush; _lightBrushes[(int)LightType.DistantDiffuse] = _distantDiffuseLightBrush; _lightBrushes[(int)LightType.DistantSpecular] = _distantSpecularLightBrush; _lightBrushes[(int)LightType.PointDiffuse] = _pointDiffuseLightBrush; _lightBrushes[(int)LightType.PointSpecular] = _pointSpecularLightBrush; _lightBrushes[(int)LightType.SpotDiffuse] = _spotDiffuseLightBrush; _lightBrushes[(int)LightType.SpotSpecular] = _spotSpecularLightBrush; //Initialize values for all light types InitializeValues(); }
private static IReadOnlyList<IImageProvider> CreateFramedAnimation(IReadOnlyList<IImageProvider> images, Rect animationBounds, int w, int h) { List<IImageProvider> framedAnimation = new List<IImageProvider>(); foreach (IImageProvider frame in images) { BlendEffect blendEffect = new BlendEffect(); blendEffect.ForegroundSource = new CropEffect(animationBounds); blendEffect.GlobalAlpha = 1.0; blendEffect.BlendFunction = BlendFunction.Normal; blendEffect.TargetArea = new Rect( animationBounds.Left / w, animationBounds.Top / h, animationBounds.Width / w, animationBounds.Height / h ); framedAnimation.Add(blendEffect); } return framedAnimation; }
private async void UpdateEffect() { if (_compositor != null) { ComboBoxItem item = EffectSelection.SelectedValue as ComboBoxItem; IGraphicsEffect graphicsEffect = null; CompositionBrush secondaryBrush = null; string[] animatableProperties = null; // // Create the appropriate effect graph and resources // switch ((EffectTypes)item.Tag) { case EffectTypes.Desaturation: { graphicsEffect = new SaturationEffect() { Saturation = 0.0f, Source = new CompositionEffectSourceParameter("ImageSource") }; } break; case EffectTypes.Hue: { graphicsEffect = new HueRotationEffect() { Name = "Hue", Angle = 3.14f, Source = new CompositionEffectSourceParameter("ImageSource") }; animatableProperties = new[] { "Hue.Angle" }; } break; case EffectTypes.VividLight: { graphicsEffect = new BlendEffect() { Mode = BlendEffectMode.VividLight, Foreground = new ColorSourceEffect() { Name = "Base", Color = Color.FromArgb(255,80,40,40) }, Background = new CompositionEffectSourceParameter("ImageSource"), }; animatableProperties = new[] { "Base.Color" }; } break; case EffectTypes.Mask: { graphicsEffect = new CompositeEffect() { Mode = CanvasComposite.DestinationOver, Sources = { new CompositeEffect() { Mode = CanvasComposite.DestinationIn, Sources = { new CompositionEffectSourceParameter("ImageSource"), new CompositionEffectSourceParameter("SecondSource") } }, new ColorSourceEffect() { Color = Color.FromArgb(200,255,255,255) }, } }; CompositionDrawingSurface backgroundSurface = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK Insider/ForegroundFocusEffects/mask.png")); CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush(backgroundSurface); maskBrush.Stretch = CompositionStretch.UniformToFill; maskBrush.CenterPoint = backgroundSurface.Size.ToVector2() / 2; secondaryBrush = maskBrush; } break; case EffectTypes.Blur: { graphicsEffect = new GaussianBlurEffect() { BlurAmount = 20, Source = new CompositionEffectSourceParameter("ImageSource"), Optimization = EffectOptimization.Balanced, BorderMode = EffectBorderMode.Hard, }; } break; case EffectTypes.LightenBlur: { graphicsEffect = new ArithmeticCompositeEffect() { Source1Amount = .4f, Source2Amount = .6f, MultiplyAmount = 0, Source1 = new ColorSourceEffect() { Name = "Base", Color = Color.FromArgb(255, 255, 255, 255), }, Source2 = new GaussianBlurEffect() { BlurAmount = 20, Source = new CompositionEffectSourceParameter("ImageSource"), Optimization = EffectOptimization.Balanced, BorderMode = EffectBorderMode.Hard, } }; } break; case EffectTypes.DarkenBlur: { graphicsEffect = new ArithmeticCompositeEffect() { Source1Amount = .4f, Source2Amount = .6f, MultiplyAmount = 0, Source1 = new ColorSourceEffect() { Name = "Base", Color = Color.FromArgb(255, 0, 0, 0), }, Source2 = new GaussianBlurEffect() { BlurAmount = 20, Source = new CompositionEffectSourceParameter("ImageSource"), Optimization = EffectOptimization.Balanced, BorderMode= EffectBorderMode.Hard, } }; } break; case EffectTypes.RainbowBlur: { graphicsEffect = new ArithmeticCompositeEffect() { Source1Amount = .3f, Source2Amount = .7f, MultiplyAmount = 0, Source1 = new ColorSourceEffect() { Name = "Base", Color = Color.FromArgb(255, 0, 0, 0), }, Source2 = new GaussianBlurEffect() { BlurAmount = 20, Source = new CompositionEffectSourceParameter("ImageSource"), Optimization = EffectOptimization.Balanced, BorderMode = EffectBorderMode.Hard, } }; animatableProperties = new[] { "Base.Color" }; } break; default: break; } // Create the effect factory and instantiate a brush CompositionEffectFactory _effectFactory = _compositor.CreateEffectFactory(graphicsEffect, animatableProperties); CompositionEffectBrush brush = _effectFactory.CreateBrush(); // Set the destination brush as the source of the image content brush.SetSourceParameter("ImageSource", _compositor.CreateBackdropBrush()); // If his effect uses a secondary brush, set it now if (secondaryBrush != null) { brush.SetSourceParameter("SecondSource", secondaryBrush); } // Update the destination layer with the fully configured brush _destinationSprite.Brush = brush; } }
public void CreatesQuiteComplexGraph() { var bitmap = new Bitmap(new Size(10, 10), ColorMode.Argb8888); using (var source1 = new BitmapImageSource(bitmap)) using (var source2 = new BitmapImageSource(bitmap)) using (var source3 = new BitmapImageSource(bitmap)) using (var source4 = new BitmapImageSource(bitmap)) using (var segmenter = new InteractiveForegroundSegmenter(source1, Color.FromArgb(255, 255, 0, 0), Color.FromArgb(255, 0, 255, 0), source2)) using (var bokeh = new LensBlurEffect(source1, segmenter)) using (var blendEffect = new BlendEffect(bokeh, source3)) { string result = CreateGraph(blendEffect); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(source1))).Matches(result).Count); Assert.AreEqual(2, new Regex(Regex.Escape(NodeId(source2))).Matches(result).Count); Assert.AreEqual(2, new Regex(Regex.Escape(NodeId(source3))).Matches(result).Count); Assert.AreEqual(0, new Regex(Regex.Escape(NodeId(source4))).Matches(result).Count); Assert.AreEqual(4, new Regex(Regex.Escape(NodeId(segmenter))).Matches(result).Count); Assert.AreEqual(5, new Regex(Regex.Escape(NodeId(bokeh))).Matches(result).Count); Assert.AreEqual(3, new Regex(Regex.Escape(NodeId(blendEffect))).Matches(result).Count); } }
private void Uninitialize() { if (_cameraPreviewImageSource != null) { _cameraPreviewImageSource.Dispose(); _cameraPreviewImageSource = null; } if (_blendEffect != null) { _blendEffect.Dispose(); _blendEffect = null; } if (_blendImageProvider != null) { _blendImageProvider = null; } }
private void BlendSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBoxItem item = BlendSelection.SelectedValue as ComboBoxItem; BlendEffectMode blendmode = (BlendEffectMode)item.Tag; // Create a chained effect graph using a BlendEffect, blending color and blur var graphicsEffect = new BlendEffect { Mode = blendmode, Background = new ColorSourceEffect() { Name = "Tint", Color = Tint.Color, }, Foreground = new GaussianBlurEffect() { Name = "Blur", Source = new CompositionEffectSourceParameter("Backdrop"), BlurAmount = (float)BlurAmount.Value, BorderMode = EffectBorderMode.Hard, } }; var blurEffectFactory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount", "Tint.Color"}); // Create EffectBrush, BackdropBrush and SpriteVisual _brush = blurEffectFactory.CreateBrush(); // If the animation is running, restart it on the new brush if (AnimateToggle.IsOn) { StartBlurAnimation(); } var destinationBrush = _compositor.CreateBackdropBrush(); _brush.SetSourceParameter("Backdrop", destinationBrush); var blurSprite = _compositor.CreateSpriteVisual(); blurSprite.Size = new Vector2((float)BackgroundImage.ActualWidth, (float)BackgroundImage.ActualHeight); blurSprite.Brush = _brush; ElementCompositionPreview.SetElementChildVisual(BackgroundImage, blurSprite); }
private void DrawFrame(CanvasDrawingSession ds) { ds.Clear(); if (_background != null) { var tile = new TileEffect(); tile.Source = _background; tile.SourceRectangle = new Rect(0, 0, 400, 400); ds.DrawImage(tile); } using (var blendDs = _buffer.CreateDrawingSession()) { blendDs.Clear(); } foreach (var layer in _layers.Reverse().Where(l => l.IsVisible)) { using (var tmpDs = _tmpBuffer.CreateDrawingSession()) { tmpDs.Clear(Colors.Transparent); switch (layer.BlendMode) { case BlendMode.Normal: tmpDs.DrawImage(_buffer); tmpDs.DrawImage(layer.Image, (float)layer.Opacity / 100); break; case BlendMode.Addition: tmpDs.DrawImage(_buffer); tmpDs.Blend = CanvasBlend.Add; tmpDs.DrawImage(layer.Image, (float)layer.Opacity / 100); break; default: using (var alpha = layer.Image.Clone()) using (var blend = new BlendEffect()) { using (var alphaDs = alpha.CreateDrawingSession()) { alphaDs.DrawImage(layer.Image, (float)layer.Opacity / 100); } blend.Background = _buffer; blend.Foreground = alpha; blend.Mode = layer.BlendMode.ToBlendEffectMode(); tmpDs.DrawImage(blend); } break; } } using (var blendDs = _buffer.CreateDrawingSession()) { blendDs.Clear(); blendDs.DrawImage(_tmpBuffer); } ds.DrawImage(_buffer); } }
private static IImageProvider CreateBlendEffect(BlendParams blendParams) { Debug.Assert(blendParams.Image.IsSynchronous); Debug.Assert(blendParams.PreviousImage.IsSynchronous); Debug.Assert(blendParams.Mask.IsSynchronous || blendParams.Mask.IsEmpty); var blendEffect = new BlendEffect(blendParams.PreviousImage.Result, blendParams.Image.Result, blendParams.Style.BlendFunction, blendParams.Style.Opacity); if (!blendParams.Mask.IsEmpty) { blendEffect.MaskSource = blendParams.Mask.Result; } if (blendParams.Style.TargetArea.HasValue) { blendEffect.TargetArea = blendParams.Style.TargetArea.Value; } return blendEffect; }
private ICanvasImage CreateLuminanceToAlpha() { var contrastAdjustedTiger = new LinearTransferEffect { Source = bitmapTiger, RedOffset = -3, GreenOffset = -3, BlueOffset = -3, }; var tigerAlpha = new LuminanceToAlphaEffect { Source = contrastAdjustedTiger }; var tigerAlphaWithWhiteRgb = new LinearTransferEffect { Source = tigerAlpha, RedOffset = 1, GreenOffset = 1, BlueOffset = 1, RedSlope = 0, GreenSlope = 0, BlueSlope = 0, }; var recombinedRgbAndAlpha = new ArithmeticCompositeEffect { Source1 = tigerAlphaWithWhiteRgb, Source2 = bitmapTiger, }; var movedTiger = new Transform2DEffect { Source = recombinedRgbAndAlpha }; const float turbulenceSize = 128; var backgroundImage = new CropEffect { Source = new TileEffect { Source = new TurbulenceEffect { Octaves = 8, Size = new Vector2(turbulenceSize), Tileable = true }, SourceRectangle= new Rect(0, 0, turbulenceSize, turbulenceSize) }, SourceRectangle = new Rect((bitmapTiger.Size.ToVector2() * -0.5f).ToPoint(), (bitmapTiger.Size.ToVector2() * 1.5f).ToPoint()) }; var tigerOnBackground = new BlendEffect { Foreground = movedTiger, Background = backgroundImage }; // Animation moves the alpha bitmap around, and alters color transfer settings to change how solid it is. animationFunction = elapsedTime => { contrastAdjustedTiger.RedSlope = contrastAdjustedTiger.GreenSlope = contrastAdjustedTiger.BlueSlope = ((float)Math.Sin(elapsedTime * 0.9) + 2) * 3; var dx = (float)Math.Cos(elapsedTime) * 50; var dy = (float)Math.Sin(elapsedTime) * 50; movedTiger.TransformMatrix = Matrix3x2.CreateTranslation(dx, dy); }; return tigerOnBackground; }
private void MainGridLoaded(object sender, RoutedEventArgs e) { m_compositor = ElementCompositionPreview.GetElementVisual(MainGrid).Compositor; m_root = m_compositor.CreateContainerVisual(); ElementCompositionPreview.SetElementChildVisual(MainGrid, m_root); Size imageSize; m_noEffectBrush = CreateBrushFromAsset( "Bruno'sFamily2015 (13)-X2.jpg", out imageSize); m_imageAspectRatio = (imageSize.Width == 0 && imageSize.Height == 0) ? 1 : imageSize.Width / imageSize.Height; m_sprite = m_compositor.CreateSpriteVisual(); ResizeImage(new Size(MainGrid.ActualWidth, MainGrid.ActualHeight)); m_root.Children.InsertAtTop(m_sprite); // Image with alpha channel as an mask. var alphaMaskEffectDesc = new CompositeEffect { Mode = CanvasComposite.DestinationIn, Sources = { new CompositionEffectSourceParameter("Image"), new Transform2DEffect { Name = "MaskTransform", Source = new CompositionEffectSourceParameter("Mask") } } }; m_alphaMaskEffectBrush = m_compositor.CreateEffectFactory( alphaMaskEffectDesc, new[] { "MaskTransform.TransformMatrix" } ).CreateBrush(); m_alphaMaskEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); m_alphaMaskEffectBrush.SetSourceParameter( "Mask", CreateBrushFromAsset("CircleMask.png")); // Arithmetic operations between two images. var arithmeticEffectDesc = new ArithmeticCompositeEffect { Name = "effect", ClampOutput = false, Source1 = new CompositionEffectSourceParameter("Source1"), Source2 = new CompositionEffectSourceParameter("Source2") }; m_arithmeticEffectBrush = m_compositor.CreateEffectFactory( arithmeticEffectDesc, new[] { "effect.MultiplyAmount", "effect.Source1Amount", "effect.Source2Amount", "effect.Offset" } ).CreateBrush(); m_arithmeticEffectBrush.SetSourceParameter( "Source1", m_noEffectBrush); m_arithmeticEffectBrush.SetSourceParameter( "Source2", CreateBrushFromAsset("_P2A8041.jpg")); // Creates a blend effect that combines two images. var foregroundBrush = CreateBrushFromAsset("Checkerboard_100x100.png"); m_blendEffectBrushes = new CompositionEffectBrush[m_supportedBlendModes.Length]; for (int i = 0; i < m_supportedBlendModes.Length; i++) { var blendEffectDesc = new BlendEffect { Mode = m_supportedBlendModes[i], Background = new CompositionEffectSourceParameter("Background"), Foreground = new CompositionEffectSourceParameter("Foreground") }; m_blendEffectBrushes[i] = m_compositor.CreateEffectFactory( blendEffectDesc ).CreateBrush(); m_blendEffectBrushes[i].SetSourceParameter( "Background", m_noEffectBrush); m_blendEffectBrushes[i].SetSourceParameter( "Foreground", foregroundBrush); } // Generates an image containing a solid color. var colorSourceEffectDesc = new ColorSourceEffect // FloodEffect { Name = "effect" }; m_colorSourceEffectBrush = m_compositor.CreateEffectFactory( colorSourceEffectDesc, new[] { "effect.Color" } ).CreateBrush(); // Changes the contrast of an image. var contrastEffectDesc = new ContrastEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_contrastEffectBrush = m_compositor.CreateEffectFactory( contrastEffectDesc, new[] { "effect.Contrast" } ).CreateBrush(); m_contrastEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Changes the exposure of an image. var exposureEffectDesc = new ExposureEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_exposureEffectBrush = m_compositor.CreateEffectFactory( exposureEffectDesc, new[] { "effect.Exposure" } ).CreateBrush(); m_exposureEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Alters the colors of an image by applying a per-channel gamma transfer function. var gammaTransferEffectDesc = new GammaTransferEffect { Name = "effect", RedDisable = false, GreenDisable = false, BlueDisable = false, AlphaDisable = false, Source = new CompositionEffectSourceParameter("Image") }; m_gammaTransferEffectBrush = m_compositor.CreateEffectFactory( gammaTransferEffectDesc, new[] { "effect.RedAmplitude", "effect.RedExponent", "effect.RedOffset", "effect.GreenAmplitude", "effect.GreenExponent", "effect.GreenOffset", "effect.BlueAmplitude", "effect.BlueExponent", "effect.BlueOffset" } ).CreateBrush(); m_gammaTransferEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Converts an image to monochromatic gray. var grayscaleEffectDesc = new GrayscaleEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_grayscaleEffectBrush = m_compositor.CreateEffectFactory( grayscaleEffectDesc ).CreateBrush(); m_grayscaleEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Alters the color of an image by rotating its hue values. var hueRotationEffectDesc = new HueRotationEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_hueRotationEffectBrush = m_compositor.CreateEffectFactory( hueRotationEffectDesc, new[] { "effect.Angle" } ).CreateBrush(); m_hueRotationEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Inverts the colors of an image. var invertEffectDesc = new InvertEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_invertEffectBrush = m_compositor.CreateEffectFactory( invertEffectDesc ).CreateBrush(); m_invertEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Alters the saturation of an image. var saturationEffectDesc = new SaturationEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_saturateEffectBrush = m_compositor.CreateEffectFactory( saturationEffectDesc, new[] { "effect.Saturation" } ).CreateBrush(); m_saturateEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Converts an image to sepia tones. var supportedAlphaModes = new[] { CanvasAlphaMode.Premultiplied, CanvasAlphaMode.Straight }; m_sepiaEffectBrushes = new CompositionEffectBrush[supportedAlphaModes.Length]; for (int i = 0; i < supportedAlphaModes.Length; i++) { var sepiaEffectDesc = new SepiaEffect { Name = "effect", AlphaMode = supportedAlphaModes[i], Source = new CompositionEffectSourceParameter("Image") }; m_sepiaEffectBrushes[i] = m_compositor.CreateEffectFactory( sepiaEffectDesc, new[] { "effect.Intensity" } ).CreateBrush(); m_sepiaEffectBrushes[i].SetSourceParameter( "Image", m_noEffectBrush); } // Adjusts the temperature and/or tint of an image. var temperatureAndTintEffectDesc = new TemperatureAndTintEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_temperatureAndTintEffectBrush = m_compositor.CreateEffectFactory( temperatureAndTintEffectDesc, new[] { "effect.Temperature", "effect.Tint" } ).CreateBrush(); m_temperatureAndTintEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // Applies a 2D affine transform matrix to an image. var transform2DEffectDesc = new Transform2DEffect { TransformMatrix = new Matrix3x2( -1, 0, 0, 1, m_sprite.Size.X, 0), Source = new CompositionEffectSourceParameter("Image") }; m_transform2DEffectBrush = m_compositor.CreateEffectFactory( transform2DEffectDesc ).CreateBrush(); m_transform2DEffectBrush.SetSourceParameter( "Image", m_noEffectBrush); // For simplying UI states switch, put effect parameter grids in an array m_effectParamsGrids = new Grid[(int)EffectType.NumEffectTypes]; m_effectParamsGrids[(int)EffectType.NoEffect] = null; m_effectParamsGrids[(int)EffectType.AlphaMask] = AlphaMaskParams; m_effectParamsGrids[(int)EffectType.Arithmetic] = ArithmeticParams; m_effectParamsGrids[(int)EffectType.Blend] = BlendParams; m_effectParamsGrids[(int)EffectType.ColorSource] = ColorSourceParams; m_effectParamsGrids[(int)EffectType.Contrast] = ContrastParams; m_effectParamsGrids[(int)EffectType.Exposure] = ExposureParams; m_effectParamsGrids[(int)EffectType.GammaTransfer] = GammaTransferParams; m_effectParamsGrids[(int)EffectType.Grayscale] = null; m_effectParamsGrids[(int)EffectType.HueRotation] = HueRotationParams; m_effectParamsGrids[(int)EffectType.Invert] = null; m_effectParamsGrids[(int)EffectType.Saturation] = SaturationParams; m_effectParamsGrids[(int)EffectType.Sepia] = SepiaParams; m_effectParamsGrids[(int)EffectType.TemperatureAndTint] = TemperatureAndTintParams; m_effectParamsGrids[(int)EffectType.Transform2D] = null; // Same as grids m_effectBrushes = new CompositionBrush[(int)EffectType.NumEffectTypes]; m_effectBrushes[(int)EffectType.NoEffect] = m_noEffectBrush; m_effectBrushes[(int)EffectType.AlphaMask] = m_alphaMaskEffectBrush; m_effectBrushes[(int)EffectType.Arithmetic] = m_arithmeticEffectBrush; m_effectBrushes[(int)EffectType.Blend] = m_blendEffectBrushes[m_activeBlendMode]; m_effectBrushes[(int)EffectType.ColorSource] = m_colorSourceEffectBrush; m_effectBrushes[(int)EffectType.Contrast] = m_contrastEffectBrush; m_effectBrushes[(int)EffectType.Exposure] = m_exposureEffectBrush; m_effectBrushes[(int)EffectType.GammaTransfer] = m_gammaTransferEffectBrush; m_effectBrushes[(int)EffectType.Grayscale] = m_grayscaleEffectBrush; m_effectBrushes[(int)EffectType.HueRotation] = m_hueRotationEffectBrush; m_effectBrushes[(int)EffectType.Invert] = m_invertEffectBrush; m_effectBrushes[(int)EffectType.Saturation] = m_saturateEffectBrush; m_effectBrushes[(int)EffectType.Sepia] = m_sepiaEffectBrushes[m_activeSepiaAlphaMode]; m_effectBrushes[(int)EffectType.TemperatureAndTint] = m_temperatureAndTintEffectBrush; m_effectBrushes[(int)EffectType.Transform2D] = m_transform2DEffectBrush; this.InitializeValues(); }
void InitializeBloomFilter() { BloomEnabled = true; // A bloom filter makes graphics appear to be bright and glowing by adding blur around only // the brightest parts of the image. This approximates the look of HDR (high dynamic range) // rendering, in which the color of the brightest light sources spills over onto surrounding // pixels. // // Many different visual styles can be achieved by adjusting these settings: // // Intensity = how much bloom is added // 0 = none // // Threshold = how bright does a pixel have to be in order for it to bloom // 0 = the entire image blooms equally // // Blur = how much the glow spreads sideways around bright areas BloomIntensity = 200; BloomThreshold = 80; BloomBlur = 48; // Before drawing, properties of these effects will be adjusted to match the // current settings (see ApplyBloomFilter), and an input image connected to // extractBrightAreas.Source and bloomResult.Background (see DemandCreateBloomRenderTarget). // Step 1: use a transfer effect to extract only pixels brighter than the threshold. extractBrightAreas = new LinearTransferEffect { ClampOutput = true, }; // Step 2: blur these bright pixels. blurBrightAreas = new GaussianBlurEffect { Source = extractBrightAreas, }; // Step 3: adjust how much bloom is wanted. adjustBloomIntensity = new LinearTransferEffect { Source = blurBrightAreas, }; // Step 4: blend the bloom over the top of the original image. bloomResult = new BlendEffect { Foreground = adjustBloomIntensity, Mode = BlendEffectMode.Screen, }; }
private ObservableCollection<VideoEffectsViewModel> CreateNonEditableEffects() { var effects = new ObservableCollection<VideoEffectsViewModel>(); m_antiqueEffect = new AntiqueEffect(); effects.Add(new VideoEffectsViewModel(m_antiqueEffect, "antique_thumbnail.jpg") { Name = "Antique" }); m_sepiaEffect = new SepiaEffect(); effects.Add(new VideoEffectsViewModel(m_sepiaEffect, "sepia_thumbnail.jpg") { Name = "Sepia" }); m_blendEffect = new BlendEffect() { GlobalAlpha = 0.5 }; effects.Add(new VideoEffectsViewModel(m_blendEffect, "blend_brokenglass_thumbnail.jpg", "BrokenGlas.png") { Name = "Blend 1" }); var effect = new BlendEffect() { BlendFunction = BlendFunction.Overlay, GlobalAlpha = 0.5 }; effects.Add(new VideoEffectsViewModel(effect, "blend_raindrops_thumbnail.jpg", "raindrops.jpg") { Name = "Blend 2" }); m_mirrorEffect = new MirrorEffect(); effects.Add(new VideoEffectsViewModel(m_mirrorEffect, "mirror_thumbnail.jpg") { Name = "Mirror" }); m_grayscaleEffect = new GrayscaleEffect(); effects.Add(new VideoEffectsViewModel(m_grayscaleEffect, "grayscale_thumbnail.jpg") { Name = "Grayscale" }); m_binaryEffect = new BinaryEffect(); effects.Add(new VideoEffectsViewModel(m_binaryEffect, "grayscale_thumbnail.jpg") { Name = "Binary" }); m_medianFilter = new MedianFilter(); effects.Add(new VideoEffectsViewModel(m_medianFilter, "grayscale_thumbnail.jpg") { Name = "Median" }); return effects; }