private async Task InitControl() { // // Create the sperical normal map. The normals will give the appearance of a sphere, and the alpha channel is used // for masking off the rectangular edges. // //CompositionDrawingSurface normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///X.UI.Composition.Assets/SphericalWithMask.png")); CompositionDrawingSurface normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///X.UI.Composition.Assets/BeveledEdges.jpg")); _circleNormalsBrush = _compositor.CreateSurfaceBrush(normalMap); _circleNormalsBrush.Stretch = CompositionStretch.Fill; // // Create the flat normal map with beveled edges. This should give the appearance of slanting of the surface along // the edges, flat in the middle. // normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///X.UI.Composition.Assets/BeveledEdges.jpg")); _flatNormalsBrush = _compositor.CreateSurfaceBrush(normalMap); _flatNormalsBrush.Stretch = CompositionStretch.Fill; // Update the effect brushes now that the normal maps are available. UpdateEffectBrush(); }
private void LoadImage(CompositionSurfaceBrush brush, Uri uri) { // Create an image source to load CompositionImage imageSource = _imageFactory.CreateImageFromUri(uri); brush.Surface = imageSource.Surface; }
/// <summary> /// Deconstructs the Composition Brush. /// </summary> protected override void OnDisconnected() { base.OnDisconnected(); if (_device != null) { _device.DeviceLost -= CanvasDevice_DeviceLost; _device = null; } if (_graphics != null) { _graphics.RenderingDeviceReplaced -= CanvasDevice_RenderingDeviceReplaced; _graphics = null; } // Dispose of composition resources when no longer in use. if (CompositionBrush != null) { CompositionBrush.Dispose(); CompositionBrush = null; } if (_surfaceBrush != null) { _surfaceBrush.Dispose(); _surfaceBrush = null; } }
/// <summary> /// Initializes new instance of the <see cref="BaseBackDrop"/> class. /// </summary> /// <param name="useHostBackdrop">Enables host backdrop is platform supports it.</param> public BaseBackDrop(bool useHostBackdrop = false) { m_rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement); Compositor = m_rootVisual.Compositor; m_blurVisual = Compositor.CreateSpriteVisual(); m_noiseBrush = Compositor.CreateSurfaceBrush(); CompositionEffectBrush brush = BuildBlurBrush(); if (useHostBackdrop && IsHostBackDropSupported) { brush.SetSourceParameter("source", m_compositor.CreateHostBackdropBrush()); } else { brush.SetSourceParameter("source", m_compositor.CreateBackdropBrush()); } m_blurBrush = brush; m_blurVisual.Brush = m_blurBrush; BlurAmount = 9; //TintColor = Colors.Transparent; ElementCompositionPreview.SetElementChildVisual(this as UIElement, m_blurVisual); this.Loading += OnLoading; this.Unloaded += OnUnloaded; }
public void Dispose() { if (_surface != null) { _surface.Dispose(); _surface = null; } if (_brush != null) { _brush.Dispose(); _brush = null; } _drawer = null; //ImageLoader.Instance.UnregisterSurface(this); }
/// <summary> /// Creates a circular solid colored brush that we can apply to a visual /// </summary> private CompositionEffectBrush CreateCircleBrushWithColor(Windows.UI.Color color) { var colorBrush = _compositor.CreateColorBrush(color); // // Because Windows.UI.Composition does not have a Circle visual, we will // work around by using a circular opacity mask // Create a simple Composite Effect, using DestinationIn (S * DA), // with a color source and a named parameter source. // var effect = new CompositeEffect { Mode = CanvasComposite.DestinationIn, Sources = { new ColorSourceEffect() { Color = color }, new CompositionEffectSourceParameter("mask") } }; var factory = _compositor.CreateEffectFactory(effect); var brush = factory.CreateBrush(); // // Create the mask brush using the circle mask // CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush(); maskBrush.Surface = _circleMaskSurface.Surface; brush.SetSourceParameter("mask", maskBrush); return(brush); }
private void InitializeCompositionVariables() { var bounds = ApplicationView.GetForCurrentView().VisibleBounds; var maxWindowWidth = bounds.Width.ToFloat(); var maxWindowHeight = bounds.Height.ToFloat(); var maxWindowRadius = Math.Max(maxWindowWidth, maxWindowHeight); // Setup sky visual's size, position, opacity, etc. _skyVisual = Sky.ContainerVisual(); _skyVisual.Size = new Vector2(maxWindowRadius * SkyVisualAreaRatio); _skyVisual.Offset = new Vector3(-SkyVisualRadius + maxWindowWidth / 2.0f, -SkyVisualRadius + maxWindowHeight / 2.0f, 0.0f); _skyVisual.CenterPoint = new Vector3(SkyVisualRadius, SkyVisualRadius, 0.0f); _skyVisual.Opacity = 0; _compositor = _skyVisual.Compositor; _reading = _compositor.CreatePropertySet(); _reading.InsertVector3("Offset", new Vector3(0.0f, 0.0f, 0.0f)); _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _circleBrush = _compositor.CreateSurfaceBrush(); _circleBrush.Surface = _imageLoader.LoadImageFromUri(new Uri(StarUriString)); if (_inclinometer != null) { SetupSkyVisualOffsetExpressionAnimation(); } }
private void LoadImage(CompositionSurfaceBrush brush) { // Create an image source to load CompositionImage imageSource = _imageFactory.CreateImageFromUri(new Uri("ms-appx:///Assets/cat.png")); brush.Surface = imageSource.Surface; }
private void SamplePage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Get backing visual from shadow container and interop compositor _shadowContainer = ElementCompositionPreview.GetElementVisual(ShadowContainer); _compositor = _shadowContainer.Compositor; // Get CompositionImage, its sprite visual _image = VisualTreeHelperExtensions.GetFirstDescendantOfType <CompositionImage>(ShadowContainer); _imageVisual = _image.SpriteVisual; // Load mask asset onto surface using helpers in SamplesCommon _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _imageMaskSurface = _imageLoader.CreateCircleSurface(200, Colors.White); // Create surface brush for mask CompositionSurfaceBrush mask = _compositor.CreateSurfaceBrush(); mask.Surface = _imageMaskSurface.Surface; // Get surface brush from composition image CompositionSurfaceBrush source = _image.SurfaceBrush as CompositionSurfaceBrush; // Create mask brush for toggle mask functionality _maskBrush = _compositor.CreateMaskBrush(); _maskBrush.Mask = mask; _maskBrush.Source = source; // Initialize toggle mask _isMaskEnabled = false; }
private async void Page_Loaded(object sender, RoutedEventArgs e) { _backgroundImageVisual = _compositor.CreateSpriteVisual(); _imageContainer = _compositor.CreateContainerVisual(); _imageSurfaceBrush = _compositor.CreateSurfaceBrush(); _capabilities.Changed += HandleCapabilitiesChanged; ElementCompositionPreview.SetElementChildVisual(ImageCanvas, _imageContainer); // Load in image var uri = new Uri("ms-appx:///Assets/Landscapes/Landscape-7.jpg"); var surface = await SurfaceLoader.LoadFromUri(uri); var imageSurface = _compositor.CreateSurfaceBrush(surface); _imageSurfaceBrush.Surface = imageSurface.Surface; _imageSurfaceBrush.Stretch = CompositionStretch.Fill; _imageContainer.Size = new Vector2((float)ImageCanvas.ActualWidth, (float)ImageCanvas.ActualHeight); _imageContainer.Children.InsertAtTop(_backgroundImageVisual); UpdateVisualSizeAndPosition(); UpdateAlbumArt(); }
public void Desaturate() { // Create and setup an instance of the effect for the visual //Create CompositionSurfaceBrush CompositionSurfaceBrush surfaceBrush = _compositor.CreateSurfaceBrush(); LoadImage(surfaceBrush, new Uri("ms-appx:///Assets/cat.png")); // Create the graphics effect var graphicsEffect = new SaturationEffect { Saturation = 0.0f, Source = new CompositionEffectSourceParameter("mySource") }; // Compile the effect var effectFactory = _compositor.CreateEffectFactory(graphicsEffect); var catEffect = effectFactory.CreateBrush(); catEffect.SetSourceParameter("mySource", surfaceBrush); // Create the visual and add it to the composition tree var catVisual = _compositor.CreateSpriteVisual(); catVisual.Brush = catEffect; catVisual.Size = new Vector2(219, 300); _root.Children.InsertAtBottom(catVisual); }
private void BackgroundImage_FirstOpened(object sender, RoutedEventArgs e) { // Image loaded, let's show the content this.Opacity = 1; // Show the content now that we should have something. ScalarKeyFrameAnimation fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation(); fadeInAnimation.InsertKeyFrame(0, 0); fadeInAnimation.InsertKeyFrame(1, 1); fadeInAnimation.Duration = TimeSpan.FromMilliseconds(1000); BackgroundImage.SpriteVisual.StartAnimation("Opacity", fadeInAnimation); ElementCompositionPreview.GetElementVisual(ImageList).StartAnimation("Opacity", fadeInAnimation); // Start a slow UV scale to create movement in the background image Vector2KeyFrameAnimation scaleAnimation = _compositor.CreateVector2KeyFrameAnimation(); scaleAnimation.InsertKeyFrame(0, new Vector2(1.1f, 1.1f)); scaleAnimation.InsertKeyFrame(.5f, new Vector2(2.0f, 2.0f)); scaleAnimation.InsertKeyFrame(1, new Vector2(1.1f, 1.1f)); scaleAnimation.Duration = TimeSpan.FromMilliseconds(40000); scaleAnimation.IterationBehavior = AnimationIterationBehavior.Forever; CompositionDrawingSurface surface = (CompositionDrawingSurface)BackgroundImage.SurfaceBrush.Surface; BackgroundImage.SurfaceBrush.CenterPoint = new Vector2((float)surface.Size.Width, (float)surface.Size.Height) * .5f; BackgroundImage.SurfaceBrush.StartAnimation("Scale", scaleAnimation); // Start the animation of the cross-fade brush so they're in sync _previousSurfaceBrush = _compositor.CreateSurfaceBrush(); _previousSurfaceBrush.StartAnimation("Scale", scaleAnimation); BackgroundImage.ImageOpened -= BackgroundImage_FirstOpened; }
protected override void OnDisconnected() { if (CompositionBrush != null) { IsConnected = false; canvasDevice.Dispose(); canvasDevice = null; graphicsDevice.Dispose(); graphicsDevice = null; surfaceBrush1.Dispose(); surfaceBrush1 = null; surfaceBrush2.Dispose(); surfaceBrush2 = null; surface1.Dispose(); surface1 = null; surface2.Dispose(); surface2 = null; Source1Animation.Dispose(); Source1Animation = null; Source2Animation.Dispose(); Source2Animation = null; colorBrush1.Dispose(); colorBrush1 = null; colorBrush2.Dispose(); colorBrush2 = null; CompositionBrush.Dispose(); CompositionBrush = null; } }
public BackDrop() { #if DEBUG if (DesignMode.DesignModeEnabled) { return; } #endif m_rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement); Compositor = m_rootVisual.Compositor; m_blurVisual = Compositor.CreateSpriteVisual(); m_noiseBrush = Compositor.CreateSurfaceBrush(); CompositionEffectBrush brush = BuildBlurBrush(); brush.SetSourceParameter("source", m_compositor.CreateBackdropBrush()); m_blurBrush = brush; m_blurVisual.Brush = m_blurBrush; BlurAmount = 9; TintColor = Colors.Transparent; ElementCompositionPreview.SetElementChildVisual(this as UIElement, m_blurVisual); this.Loading += OnLoading; this.Unloaded += OnUnloaded; }
public OverlayScreenCaptureCaptureHandler(Compositor c) { __compositor = c; __device = Direct3D11Helper.CreateDevice(); // Setup the root. __root = __compositor.CreateContainerVisual(); __root.RelativeSizeAdjustment = Vector2.One; // Setup the content. __brush = __compositor.CreateSurfaceBrush(); __brush.HorizontalAlignmentRatio = 0.5f; __brush.VerticalAlignmentRatio = 0.5f; __brush.Stretch = CompositionStretch.Uniform; var shadow = __compositor.CreateDropShadow(); shadow.Mask = __brush; __content = __compositor.CreateSpriteVisual(); __content.AnchorPoint = new Vector2(0.5f); __content.RelativeOffsetAdjustment = new Vector3(0.5f, 0.5f, 0); __content.RelativeSizeAdjustment = Vector2.One; __content.Brush = __brush; __content.Shadow = shadow; __root.Children.InsertAtTop(__content); }
private void InitializeBrushes() { if (this.DataContext is ViewImageEditorMetadata) { var viewImageEditorMetadata = (ViewImageEditorMetadata)this.DataContext; // noeffect brush Size imageSize; //m_noEffectBrush = CreateBrushFromAsset("xxxxx.jpg", out imageSize); m_noEffectBrush = CreateBrushFromAsset(viewImageEditorMetadata.Bitmap, out imageSize); m_imageAspectRatio = (imageSize.Width == 0 && imageSize.Height == 0) ? 1 : imageSize.Width / imageSize.Height; renderSurface.UpdateLayout(); ResizeImage(new Size(renderSurface.ActualWidth, renderSurface.ActualHeight)); // Exposure var exposureEffectDesc = new ExposureEffect { Name = "effect", Source = new CompositionEffectSourceParameter("Image") }; m_exposureEffectBrush = m_compositor.CreateEffectFactory(exposureEffectDesc, new[] { "effect.Exposure" }).CreateBrush(); ChangeExposureValue(0.5f); m_exposureEffectBrush.SetSourceParameter("Image", m_noEffectBrush); // 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); } }
private void Page_Loaded(object sender, RoutedEventArgs e) { _imageBrush = _compositor.CreateSurfaceBrush(); _sprite = _compositor.CreateSpriteVisual(); _sprite.Size = new Vector2((float)BorderImage.ActualWidth, (float)BorderImage.ActualHeight); ElementCompositionPreview.SetElementChildVisual(BorderImage, _sprite); IList <ComboBoxItem> imageList = new List <ComboBoxItem>(); SetComboBoxList <ImageName>(imageList); ImageSelector.ItemsSource = imageList; ImageSelector.SelectedIndex = 0; IList <ComboBoxItem> extendXList = new List <ComboBoxItem>(); SetComboBoxList <CanvasEdgeBehavior>(extendXList); ExtendXBox.ItemsSource = extendXList; ExtendXBox.SelectedIndex = 0; IList <ComboBoxItem> extendYList = new List <ComboBoxItem>(); SetComboBoxList <CanvasEdgeBehavior>(extendYList); ExtendYBox.ItemsSource = extendYList; ExtendYBox.SelectedIndex = 0; }
private void CompositionHostControl_Loaded(object sender, RoutedEventArgs e) { _currentDpi = WindowsMedia.VisualTreeHelper.GetDpi(this); _rectWidth = CompositionHostElement.ActualWidth / 2; _rectHeight = CompositionHostElement.ActualHeight / 2; // Get graphics device. _compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice); // Create surface. var noiseDrawingSurface = _compositionGraphicsDevice.CreateDrawingSurface( new Windows.Foundation.Size(_rectWidth, _rectHeight), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); // Draw to surface and create surface brush. var noiseFilePath = AppDomain.CurrentDomain.BaseDirectory + "Assets\\NoiseAsset_256X256.png"; LoadSurface(noiseDrawingSurface, noiseFilePath); _noiseSurfaceBrush = _compositor.CreateSurfaceBrush(noiseDrawingSurface); // Add composition content to tree. _compositionHost.SetChild(_containerVisual); AddCompositionContent(); ToggleAcrylic(); }
private void BuildForeground() { _foregroundBrush = _compositor.CreateSurfaceBrush(_uriSurface.Surface); _foregroundBrush.Stretch = CompositionStretch.Uniform; ForegroundVisual.Brush = _foregroundBrush; // ensure the image size accounts for the margin ForegroundVisual.Size = new Vector2( (float)ActualWidth - (float)ImageMargin.Left - (float)ImageMargin.Right, (float)ActualHeight - (float)ImageMargin.Top - (float)ImageMargin.Bottom); HandleAlignments(); if (_foregroundVisualShadow == null) { _foregroundVisualShadow = _compositor.CreateDropShadow(); _foregroundVisualShadow.Color = Color.FromArgb(255, 75, 75, 80); _foregroundVisualShadow.BlurRadius = 15.0f; _foregroundVisualShadow.Offset = new Vector3(2.5f, 2.5f, 0.0f); ForegroundVisual.Shadow = _foregroundVisualShadow; } _foregroundVisualShadow.Mask = _foregroundBrush; var offsetAnimation = _compositor.CreateVector3KeyFrameAnimation(); offsetAnimation.Target = nameof(Visual.Offset); offsetAnimation.InsertExpressionKeyFrame(1.0f, "this.FinalValue"); offsetAnimation.Duration = TimeSpan.FromMilliseconds(1500); var foregroundVisualImplicitAnimations = _compositor.CreateImplicitAnimationCollection(); foregroundVisualImplicitAnimations[nameof(Visual.Offset)] = offsetAnimation; ForegroundVisual.ImplicitAnimations = foregroundVisualImplicitAnimations; }
public BackDrop() { m_rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement); Compositor = m_rootVisual.Compositor; m_blurVisual = Compositor.CreateSpriteVisual(); #if SDKVERSION_INSIDER m_noiseBrush = Compositor.CreateSurfaceBrush(); CompositionEffectBrush brush = BuildBlurBrush(); brush.SetSourceParameter("source", m_compositor.CreateBackdropBrush()); m_blurBrush = brush; m_blurVisual.Brush = m_blurBrush; BlurAmount = 9; TintColor = Colors.Transparent; #else m_blurBrush = Compositor.CreateColorBrush(Colors.White); m_blurVisual.Brush = m_blurBrush; #endif ElementCompositionPreview.SetElementChildVisual(this as UIElement, m_blurVisual); this.Loading += OnLoading; this.Unloaded += OnUnloaded; }
/// <summary> /// Initializes the Composition Brush. /// </summary> protected override void OnConnected() { base.OnConnected(); // Delay creating composition resources until they're required. if (CompositionBrush == null) { // Abort if effects aren't supported. if (!CompositionCapabilities.GetForCurrentView().AreEffectsSupported()) { return; } var size = new Vector2(SurfaceWidth, SurfaceHeight); var device = CanvasDevice.GetSharedDevice(); var graphics = CanvasComposition.CreateCompositionGraphicsDevice(Window.Current.Compositor, device); var surface = graphics.CreateDrawingSurface(size.ToSize(), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); using (var session = CanvasComposition.CreateDrawingSession(surface)) { // Call Implementor to draw on session. if (!OnDraw(device, session, size)) { return; } } _surfaceBrush = Window.Current.Compositor.CreateSurfaceBrush(surface); _surfaceBrush.Stretch = CompositionStretch.Fill; CompositionBrush = _surfaceBrush; } }
public FrameServerHandler(MediaPlayer player, FrameworkElement container, string id, IPropertySet properties) { CanvasDevice = CanvasDevice.GetSharedDevice(); Container = container; ID = id; Player = player; ContainerVisual = ElementCompositionPreview.GetElementVisual(container); Compositor = ContainerVisual.Compositor; CompositionDevice = CanvasComposition.CreateCompositionGraphicsDevice(Compositor, CanvasDevice); SpriteVisual = Compositor.CreateSpriteVisual(); SurfaceBrush = Compositor.CreateSurfaceBrush(); SpriteVisual.Brush = SurfaceBrush; SurfaceBrush.Stretch = CompositionStretch.Uniform; ElementCompositionPreview.SetElementChildVisual(container, SpriteVisual); var sizeAni = Compositor.CreateExpressionAnimation("Container.Size"); sizeAni.SetReferenceParameter("Container", ContainerVisual); SpriteVisual.StartAnimation("Size", sizeAni); CanvasDevice.DeviceLost += CanvasDevice_DeviceLost; Container.SizeChanged += Container_SizeChanged; player.IsVideoFrameServerEnabled = true; player.VideoFrameAvailable += Player_VideoFrameAvailable; player.MediaOpened += Player_MediaOpened; //createDestinationTarget(); }
public CompositionImage() { this.DefaultStyleKey = typeof(CompositionImage); this.Background = new SolidColorBrush(Colors.Transparent); this._stretchMode = CompositionStretch.Uniform; this.Loading += CompImage_Loading; this.Unloaded += CompImage_Unloaded; this.SizeChanged += CompImage_SizeChanged; _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; // Intialize the statics as needed if (!_staticsInitialized) { _defaultPlaceholderBrush = _compositor.CreateColorBrush(Colors.DarkGray); TimeSpan duration = TimeSpan.FromMilliseconds(1000); _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation(); _fadeOutAnimation.InsertKeyFrame(0, 1); _fadeOutAnimation.InsertKeyFrame(1, 0); _fadeOutAnimation.Duration = duration; _scaleAnimation = _compositor.CreateVector2KeyFrameAnimation(); _scaleAnimation.InsertKeyFrame(0, new Vector2(1.25f, 1.25f)); _scaleAnimation.InsertKeyFrame(1, new Vector2(1, 1)); _scaleAnimation.Duration = duration; _staticsInitialized = true; } _placeholderDelay = TimeSpan.FromMilliseconds(50); _surfaceBrush = _compositor.CreateSurfaceBrush(null); }
private void Form1_Load(object sender, EventArgs e) { // This container visual is optional - content could go directly into the root // containerVisual. This lets you overlay just the picture box, and you could add // other container visuals to overlay other areas of the UI. pictureOverlayVisual = compositor.CreateContainerVisual(); pictureOverlayVisual.Offset = new Vector3(pictureBox1.Bounds.Left, pictureBox1.Bounds.Top, 0); pictureOverlayVisual.Size = new Vector2(pictureBox1.Width, pictureBox1.Height); containerVisual.Children.InsertAtTop(pictureOverlayVisual); rectWidth = pictureBox1.Width / 2; rectHeight = pictureBox1.Height / 2; // Get graphics device. compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, canvasDevice); // Create surface. var noiseDrawingSurface = compositionGraphicsDevice.CreateDrawingSurface( new Windows.Foundation.Size(rectWidth, rectHeight), DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); // Draw to surface and create surface brush. var noiseFilePath = AppDomain.CurrentDomain.BaseDirectory + "Assets\\NoiseAsset_256X256.png"; LoadSurface(noiseDrawingSurface, noiseFilePath); noiseSurfaceBrush = compositor.CreateSurfaceBrush(noiseDrawingSurface); // Add composition content to tree. AddCompositionContent(); }
public BackDrop() { m_rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement); Compositor = m_rootVisual.Compositor; m_blurVisual = Compositor.CreateSpriteVisual(); #if SDKVERSION_14393 m_noiseBrush = Compositor.CreateSurfaceBrush(); CompositionEffectBrush brush = BuildBlurBrush(); brush.SetSourceParameter("source", m_compositor.CreateBackdropBrush()); m_blurBrush = brush; m_blurVisual.Brush = m_blurBrush; BlurAmount = 9; TintColor = Colors.Transparent; #else m_blurBrush = Compositor.CreateColorBrush(Colors.White); m_blurVisual.Brush = m_blurBrush; #endif ElementCompositionPreview.SetElementChildVisual(this as UIElement, m_blurVisual); this.Loading += OnLoading; this.Unloaded += OnUnloaded; }
private void Initialize(StreamingContext context) { _type = LayerType.Image; _brush = Window.Current.Compositor.CreateSurfaceBrush(); _nineGrid = Window.Current.Compositor.CreateNineGridBrush(); _inputEffect = new BorderEffect() { Name = _id, Source = new CompositionEffectSourceParameter(_id + "Image"), }; _properties = new List <LayerProperty>(); _properties.Add(new LayerProperty("Offset", _brush)); _properties.Add(new LayerProperty("Scale", _brush)); _properties.Add(new LayerProperty("RotationAngleInDegrees", _brush)); _properties.Add(new LayerProperty("AnchorPoint", _brush)); _properties.Add(new LayerProperty("Stretch", _brush)); _properties.Add(new LayerProperty("HorizontalAlignmentRatio", _brush)); _properties.Add(new LayerProperty("VerticalAlignmentRatio", _brush)); _properties.Add(new LayerProperty("ExtendX", _inputEffect)); _properties.Add(new LayerProperty("ExtendY", _inputEffect)); _properties.Add(new LayerProperty("LeftInset", _nineGrid)); _properties.Add(new LayerProperty("TopInset", _nineGrid)); _properties.Add(new LayerProperty("RightInset", _nineGrid)); _properties.Add(new LayerProperty("BottomInset", _nineGrid)); _properties.Add(new LayerProperty("LeftInsetScale", _nineGrid)); _properties.Add(new LayerProperty("TopInsetScale", _nineGrid)); _properties.Add(new LayerProperty("RightInsetScale", _nineGrid)); _properties.Add(new LayerProperty("BottomInsetScale", _nineGrid)); _properties.Add(new LayerProperty("IsCenterHollow", _nineGrid)); }
public BasicSampleApplication(Compositor c) { compositor = c; device = Direct3D11Helper.CreateDevice(); // Setup the root. root = compositor.CreateContainerVisual(); root.RelativeSizeAdjustment = Vector2.One; // Setup the content. brush = compositor.CreateSurfaceBrush(); brush.HorizontalAlignmentRatio = 0.5f; brush.VerticalAlignmentRatio = 0.5f; brush.Stretch = CompositionStretch.Uniform; var shadow = compositor.CreateDropShadow(); shadow.Mask = brush; content = compositor.CreateSpriteVisual(); content.AnchorPoint = new Vector2(0.5f); content.RelativeOffsetAdjustment = new Vector3(0.5f, 0.5f, 0); content.RelativeSizeAdjustment = Vector2.One; content.Size = new Vector2(-80, -80); content.Brush = brush; content.Shadow = shadow; root.Children.InsertAtTop(content); }
protected override void OnConnected() { // return if Uri String is null or empty if (String.IsNullOrEmpty(ImageUriString)) { return; } Compositor compositor = Window.Current.Compositor; // Use LoadedImageSurface API to get ICompositionSurface from image uri provided _surface = LoadedImageSurface.StartLoadFromUri(new Uri(ImageUriString)); // Load Surface onto SurfaceBrush _surfaceBrush = compositor.CreateSurfaceBrush(_surface); _surfaceBrush.Stretch = CompositionStretch.UniformToFill; // CompositionCapabilities: Are Tint+Temperature and Saturation supported? bool usingFallback = !CompositionCapabilities.GetForCurrentView().AreEffectsSupported(); if (usingFallback) { // If Effects are not supported, Fallback to image without effects CompositionBrush = _surfaceBrush; return; } // Define Effect graph IGraphicsEffect graphicsEffect = new SaturationEffect { Name = "Saturation", Saturation = 0.3f, Source = new TemperatureAndTintEffect { Name = "TempAndTint", Temperature = 0, Source = new CompositionEffectSourceParameter("Surface"), } }; // Create EffectFactory and EffectBrush CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "TempAndTint.Temperature" }); CompositionEffectBrush effectBrush = effectFactory.CreateBrush(); effectBrush.SetSourceParameter("Surface", _surfaceBrush); // Set EffectBrush to paint Xaml UIElement CompositionBrush = effectBrush; // Trivial looping animation to demonstrate animated effect ScalarKeyFrameAnimation tempAnim = compositor.CreateScalarKeyFrameAnimation(); tempAnim.InsertKeyFrame(0, 0); tempAnim.InsertKeyFrame(0.5f, 1f); tempAnim.InsertKeyFrame(1, 0); tempAnim.Duration = TimeSpan.FromSeconds(5); tempAnim.IterationBehavior = Windows.UI.Composition.AnimationIterationBehavior.Forever; effectBrush.Properties.StartAnimation("TempAndTint.Temperature", tempAnim); }
async Task CreateTintEffectBrushAsync(Uri uri) { Xamarin.Forms.Image element = this.Element as Xamarin.Forms.Image; if (Control == null || Element == null || element.Width < 0 || element.Height < 0) { return; } SetupCompositor(); spriteVisual = compositor.CreateSpriteVisual(); spriteVisual.Size = new Vector2((float)element.Width, (float)element.Height); imageSurface = await generator.CreateImageSurfaceAsync(uri, new Windows.Foundation.Size(element.Width, element.Height), ImageSurfaceOptions.DefaultOptimized); CompositionSurfaceBrush surfaceBrush = compositor.CreateSurfaceBrush(imageSurface.Surface); CompositionBrush targetBrush = surfaceBrush; if (this.TintColor == Color.Transparent) { // Don't apply tint effect effectBrush = null; } else { // Set target brush to tint effect brush Windows.UI.Color nativeColor = GetNativeColor(this.TintColor); IGraphicsEffect graphicsEffect = new CompositeEffect { Mode = CanvasComposite.DestinationIn, Sources = { new ColorSourceEffect { Name = "colorSource", Color = nativeColor }, new CompositionEffectSourceParameter("mask") } }; CompositionEffectFactory effectFactory = compositor.CreateEffectFactory(graphicsEffect, new[] { "colorSource.Color" }); effectBrush = effectFactory.CreateBrush(); effectBrush.SetSourceParameter("mask", surfaceBrush); SetTint(nativeColor); targetBrush = effectBrush; } spriteVisual.Brush = targetBrush; ElementCompositionPreview.SetElementChildVisual(Control, spriteVisual); }
public SurfaceNineGridScenario(Compositor compositor, CompositionSurfaceBrush surfaceBrush, string text) { _nineGridBrush = compositor.CreateNineGridBrush(); _nineGridBrush.Source = surfaceBrush; _nineGridBrush.SetInsets(60.0f); _text = text; }
/// <summary> /// Initialize Composition /// </summary> private void InitializeComposition() { // Retrieve an instance of the Compositor from the backing Visual of the Page _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; // Create a root visual from the Compositor _root = _compositor.CreateContainerVisual(); // Set the root ContainerVisual as the XAML Page Visual ElementCompositionPreview.SetElementChildVisual(this, _root); // Assign initial values to variables used to store updated offsets for the visuals float posXUpdated = _posX; float posYUpdated = _posY; // Create a list of image brushes that can be applied to a visual string[] imageNames = { "01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "60Banana.png", "60Lemon.png", "60Vanilla.png", "60Mint.png", "60Orange.png", "110Strawberry.png", "60SprinklesRainbow.png" }; List <CompositionSurfaceBrush> imageBrushList = new List <CompositionSurfaceBrush>(); IImageLoader imageFactory = ImageLoaderFactory.CreateImageLoader(_compositor); for (int k = 0; k < imageNames.Length; k++) { var surface = imageFactory.LoadImageFromUri(new Uri("ms-appx:///Assets/Images/Composition/ImplicitAnimation/" + imageNames[k])); imageBrushList.Add(_compositor.CreateSurfaceBrush(surface)); } // Create nxn matrix of visuals where n=row/ColumnCount-1 and passes random image brush to the function // that creates a visual for (int i = 1; i < _rowCount; i++) { posXUpdated = i * _distance; for (int j = 1; j < _columnCount; j++) { CompositionSurfaceBrush brush = imageBrushList[randomBrush.Next(imageBrushList.Count)]; posYUpdated = j * _distance; _root.Children.InsertAtTop(CreateChildElement(brush, posXUpdated, posYUpdated)); } } EnableAnimationOnChildren(EnableAnimations.IsChecked.GetValueOrDefault()); }
public CompositionImage() { this.DefaultStyleKey = typeof(CompositionImage); this.Background = new SolidColorBrush(Colors.Transparent); this._stretchMode = CompositionStretch.Uniform; this.Loading += CompImage_Loading; this.Unloaded += CompImage_Unloaded; this.SizeChanged += CompImage_SizeChanged; _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; // Intialize the statics as needed if (!_staticsInitialized) { _defaultPlaceholderBrush = _compositor.CreateColorBrush(Colors.DarkGray); TimeSpan duration = TimeSpan.FromMilliseconds(1000); _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation(); _fadeOutAnimation.InsertKeyFrame(0, 1); _fadeOutAnimation.InsertKeyFrame(1, 0); _fadeOutAnimation.Duration = duration; _scaleAnimation = _compositor.CreateVector2KeyFrameAnimation(); _scaleAnimation.InsertKeyFrame(0, new Vector2(1.25f, 1.25f)); _scaleAnimation.InsertKeyFrame(1, new Vector2(1, 1)); _scaleAnimation.Duration = duration; _staticsInitialized = true; } // Initialize the surface loader if needed if (!SurfaceLoader.IsInitialized) { SurfaceLoader.Initialize(ElementCompositionPreview.GetElementVisual(this).Compositor); } _placeholderDelay = TimeSpan.FromMilliseconds(50); _surfaceBrush = _compositor.CreateSurfaceBrush(null); }
public void Dispose() { imageFactory = null; imageSource = null; if (effect != null) { effect.Dispose(); effect = null; } if (surfaceBrush != null) { surfaceBrush.Surface = null; surfaceBrush.Dispose(); surfaceBrush = null; } //if (visual != null) //{ // if(spriteVisual!=null) visual.Children.Remove(spriteVisual); // visual.Dispose(); // visual = null; //} if (effectBrush != null) { effectBrush.SetSourceParameter(EffectSource, null); effectBrush.Dispose(); effectBrush = null; } if (spriteVisual != null) { spriteVisual.Brush = null; spriteVisual.Dispose(); spriteVisual = null; } }
//private async Task HideStatusBar() //{ // //if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1, 0)) // //{ // // var statusBar = StatusBar.GetForCurrentView(); // // await statusBar.HideAsync(); // //} //} private void InitializeCompositionVariables() { var bounds = ApplicationView.GetForCurrentView().VisibleBounds; var maxWindowWidth = bounds.Width.ToFloat(); var maxWindowHeight = bounds.Height.ToFloat(); var maxWindowRadius = Math.Max(maxWindowWidth, maxWindowHeight); // Setup sky visual's size, position, opacity, etc. _skyVisual = Sky.ContainerVisual(); _skyVisual.Size = new Vector2(maxWindowRadius * SkyVisualAreaRatio); _skyVisual.Offset = new Vector3(-SkyVisualRadius + maxWindowWidth / 2.0f, -SkyVisualRadius + maxWindowHeight / 2.0f, 0.0f); _skyVisual.CenterPoint = new Vector3(SkyVisualRadius, SkyVisualRadius, 0.0f); _skyVisual.Opacity = 0; _compositor = _skyVisual.Compositor; _reading = _compositor.CreatePropertySet(); _reading.InsertVector3("Offset", new Vector3(0.0f, 0.0f, 0.0f)); _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _circleBrush = _compositor.CreateSurfaceBrush(); _circleBrush.Surface = _imageLoader.LoadImageFromUri(new Uri(StarUriString)); if (_inclinometer != null) SetupSkyVisualOffsetExpressionAnimation(); }
private void CreateSurface() { surfaceBrush = compositor.CreateSurfaceBrush(); var uriSource = UriManager.GetFilUriFromString(Source); imageSource = imageFactory.CreateImageFromUri(uriSource); surfaceBrush.Surface = imageSource.Surface; }
/// <summary> /// Creates a visible element in our application /// </summary> /// <param name="brush"></param> /// <param name="positionX"></param> /// <param name="positionY"></param> /// <returns> </returns> Visual CreateChildElement(CompositionSurfaceBrush brush, float positionX, float positionY) { // Each element consists of a single Sprite visual SpriteVisual visual = _compositor.CreateSpriteVisual(); // Create a SpriteVisual with size, offset and center point visual.Size = new Vector2(50, 50); visual.Offset = new Vector3(positionX, positionY, 0); visual.CenterPoint = new Vector3(visual.Size.X / 2.0f, visual.Size.Y / 2.0f, 0.0f); //apply the random image brush to a visual visual.Brush = brush; return visual; }
private async Task<bool> CreateSurface() { surfaceBrush = compositor.CreateSurfaceBrush(); //var uriSource = UriManager.GetFilUriFromString(Source); //imageSource = imageFactory.CreateImageFromUri(uriSource); try { var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(Source); if (file != null) { imageSource = imageFactory.CreateImageFromFile(file); surfaceBrush.Surface = imageSource.Surface; surfaceBrush.Stretch = CompositionStretch.UniformToFill; } } catch //(Exception ex) { return false; } return true; }
/// <summary> /// Creates the CompositionSurfaceBrush if one hasn't already been created. Also assigns the /// brush to the video SpriteVisual. /// </summary> private void EnsureVideoBrush() { if (_videoSurface == null) { // Getting the surface that represents the MediaPlayer's swapchain for video content // is easy, just pass a Compositor to the MediaPlayer! _videoSurface = _mediaPlayer.GetSurface(_compositor); // Create a brush for our new surface and attach it to our visual. _videoBrush = _compositor.CreateSurfaceBrush(_videoSurface.CompositionSurface); _videoVisual.Brush = _videoBrush; } }
/// <summary> /// Creates the circle used in the circle brush if not already created. /// </summary> private void EnsureCircleBrush() { if (_circleBrush == null) { _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _circleSurface = _imageLoader.CreateManagedSurfaceFromUri(new Uri(CircleImagePath)); _circleBrush = _compositor.CreateSurfaceBrush(_circleSurface.Surface); } }
private Visual AddImage(CompositionSurfaceBrush imageBrush, NodeInfo nodeInfo, float defaultOpacity = 1.0f, bool applyDistanceEffects = true) { var sprite = _compositor.CreateSpriteVisual(); var size = ((CompositionDrawingSurface)imageBrush.Surface).Size; size.Width *= nodeInfo.Scale; size.Height *= nodeInfo.Scale; sprite.Size = new Vector2((float)size.Width, (float)size.Height); sprite.AnchorPoint = new Vector2(0.5f, 0.5f); sprite.Offset = nodeInfo.Offset; _worldContainer.Children.InsertAtTop(sprite); if (applyDistanceEffects) { // // Use an ExpressionAnimation to fade the image out when it goes too close or // too far away from the camera. // if (_opacityAnimation == null) { _opacityAnimation = _compositor.CreateExpressionAnimation(@"defaultOpacity * (this.target.Offset.z + world.Offset.z > -200 ? (1 - (clamp(this.target.Offset.z + world.Offset.z, 0, 300) / 300)) : (clamp(this.target.Offset.z + world.Offset.z + 1300, 0, 300) / 300))"); _opacityAnimation.SetReferenceParameter("world", _worldContainer); } _opacityAnimation.SetScalarParameter("defaultOpacity", defaultOpacity); sprite.StartAnimation("Opacity", _opacityAnimation); } sprite.Brush = imageBrush; return sprite; }
async private void LoadImages() { int loadedImageCount = 0; // Create the loader _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); // // Populate/load our unique list of image textures. // for (int i = 0; i < (int)NamedImage.Count; i++) { var name = (NamedImage)i; Uri uri = new Uri($"ms-appx:///Assets/Photos/{name.ToString()}.jpg"); _managedSurfaces[i] = _imageLoader.CreateManagedSurfaceFromUri(uri); var surface = await _imageLoader.LoadImageFromUriAsync(uri); _imageBrushes[i] = _compositor.CreateSurfaceBrush(surface); loadedImageCount++; } // // Populate/load our unique list of "text" image textures. // _textBrushes = new CompositionSurfaceBrush[_textNodes.Length]; for (int i = 0; i < _textNodes.Length; i++) { var textNode = _textNodes[i]; var textSurface = SurfaceLoader.LoadText(textNode.Text, new Size(textNode.TextureSize.X, textNode.TextureSize.Y), textNode.TextFormat, Colors.Black, Colors.Transparent); _textBrushes[i] = _compositor.CreateSurfaceBrush(textSurface); // // Remember the index of the brush so that we can refer to it later. // textNode.BrushIndex = i; loadedImageCount++; } // // Once we've loaded all of the images, we can continue populating the world. // if (loadedImageCount == _imageBrushes.Length + _textBrushes.Length) { PopulateWorld(); } }
private async void Page_Loaded(object sender, RoutedEventArgs e) { // Populate the light type combobox IList<ComboBoxItem> lightList = new List<ComboBoxItem>(); foreach (LightingTypes type in Enum.GetValues(typeof(LightingTypes))) { ComboBoxItem item = new ComboBoxItem(); item.Tag = type; item.Content = type.ToString(); lightList.Add(item); } LightingSelection.ItemsSource = lightList; LightingSelection.SelectedIndex = 0; ThumbnailList.ItemsSource = Model.Items; // // Create the sperical normal map. The normals will give the appearance of a sphere, and the alpha channel is used // for masking off the rectangular edges. // CompositionDrawingSurface normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK Insider/ThumbnailLighting/SphericalWithMask.png")); _circleNormalsBrush = _compositor.CreateSurfaceBrush(normalMap); _circleNormalsBrush.Stretch = CompositionStretch.Fill; // // Create the flat normal map with beveled edges. This should give the appearance of slanting of the surface along // the edges, flat in the middle. // normalMap = await SurfaceLoader.LoadFromUri(new Uri("ms-appx:///Samples/SDK Insider/ThumbnailLighting/BeveledEdges.jpg")); _flatNormalsBrush = _compositor.CreateSurfaceBrush(normalMap); _flatNormalsBrush.Stretch = CompositionStretch.Fill; // Update the effect brushes now that the normal maps are available. UpdateEffectBrush(); }
private void AddImageSpriteVisual( CompositionSurfaceBrush brush, Vector2 size, ContainerVisual parent) { var imageSpriteVisual = _compositor.CreateSpriteVisual(); brush.Stretch = CompositionStretch.UniformToFill; imageSpriteVisual.Brush = brush; imageSpriteVisual.Size = size; parent.Children.InsertAtTop(imageSpriteVisual); }
internal void SetForeground(string newUri) { var newImageBrush = CreateImageBrush(newUri); Brush.SetSourceParameter("Source1", newImageBrush); if (LastImageBrush == null) { Brush.SetSourceParameter("Source2", newImageBrush); Animate(false); } else { Brush.SetSourceParameter("Source2", LastImageBrush); Animate(); } LastImageBrush = newImageBrush; }
/// <summary> /// Initializes the Composition elements /// </summary> private void InitComposition() { // Compositor _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; // CompositionGenerator _generator = CompositionGeneratorFactory.GetCompositionGenerator(_compositor); // Fade Out Animation _fadeOutAnimation = _compositor.CreateScalarKeyFrameAnimation(); _fadeOutAnimation.InsertKeyFrame(1f, 0); _fadeOutAnimation.Duration = TransitionDuration; // Fade In Animation _fadeInAnimation = _compositor.CreateScalarKeyFrameAnimation(); _fadeInAnimation.InsertKeyFrame(1f, 1); _fadeInAnimation.Duration = TransitionDuration; // Color Animation _colorAnimation = _compositor.CreateColorKeyFrameAnimation(); _colorAnimation.Duration = TransitionDuration; // Offset Animation _offsetAnimation = _compositor.CreateVector3KeyFrameAnimation(); _offsetAnimation.Target = "Offset"; _offsetAnimation.Duration = TransitionDuration; _offsetAnimation.InsertKeyFrame(1f, Vector3.Zero); // Alignment animations _alignXAnimation = _compositor.CreateScalarKeyFrameAnimation(); _alignXAnimation.Duration = AlignmentTransitionDuration; _alignYAnimation = _compositor.CreateScalarKeyFrameAnimation(); _alignYAnimation.Duration = AlignmentTransitionDuration; // ZoomIn Animation Group _scaleAnimation = _compositor.CreateVector3KeyFrameAnimation(); _scaleAnimation.Target = "Scale"; _scaleAnimation.InsertKeyFrame(1f, Vector3.One); _scaleAnimation.Duration = TransitionDuration; _zoomInAnimationGroup = _compositor.CreateAnimationGroup(); _zoomInAnimationGroup.Add(_scaleAnimation); _zoomInAnimationGroup.Add(_offsetAnimation); // Visuals _rootContainer = _compositor.CreateContainerVisual(); _frameLayer = _compositor.CreateLayerVisual(); _frameBackgroundVisual = _compositor.CreateSpriteVisual(); _frameContentVisual = _compositor.CreateSpriteVisual(); _placeholderContentVisual = _compositor.CreateSpriteVisual(); _placeholderBackgroundVisual = _compositor.CreateSpriteVisual(); _nextVisualContent = _compositor.CreateSpriteVisual(); _frameLayer.Children.InsertAtTop(_frameBackgroundVisual); _frameLayer.Children.InsertAtTop(_frameContentVisual); _frameLayer.Children.InsertAtTop(_placeholderBackgroundVisual); _frameLayer.Children.InsertAtTop(_placeholderContentVisual); _frameLayer.Children.InsertAtTop(_nextVisualContent); // Placeholder content _placeholderContentMask = _generator.CreateGeometrySurface(PlaceholderSize, GetPlaceHolderGeometry(), PlaceholderColor, PlaceholderBackground); _placeholderContentBrush = _compositor.CreateSurfaceBrush(_placeholderContentMask.Surface); _placeholderContentVisual.Brush = _placeholderContentBrush; // Placeholder background _placeholderBackgroundVisual.Brush = _compositor.CreateColorBrush(PlaceholderBackground); // By default placeholder visual will not be visible HidePlaceholder(); // Shadow visual _shadowVisual = _compositor.CreateSpriteVisual(); _rootContainer.Children.InsertAtBottom(_shadowVisual); _rootContainer.Children.InsertAtTop(_frameLayer); _frameBackgroundVisual.Brush = _compositor.CreateColorBrush(FrameBackground); // Create the effect to create the opacity mask var layerEffect = new CompositeEffect { // CanvasComposite.DestinationIn - Intersection of source and mask. // Equation: O = MA * S // where O - Output pixel, MA - Mask Alpha, S - Source pixel. Mode = CanvasComposite.DestinationIn, Sources = { new CompositionEffectSourceParameter("source"), new CompositionEffectSourceParameter("mask") } }; var layerEffectFactory = _compositor.CreateEffectFactory(layerEffect); _layerEffectBrush = layerEffectFactory.CreateBrush(); // The mask for the imageFrame _frameLayerMask = _generator.CreateMaskSurface(new Size(0, 0), null); _layerEffectBrush.SetSourceParameter("mask", _compositor.CreateSurfaceBrush(_frameLayerMask.Surface)); // Apply the mask effect to the frameLayer _frameLayer.Effect = _layerEffectBrush; ElementCompositionPreview.SetElementChildVisual(this, _rootContainer); }
/// <summary> /// Loads an image asynchronously from the given object for the given size /// </summary> /// <param name="scheduledObject">The next object to load</param> /// <param name="size">Render size of the image</param> /// <returns>Task</returns> private async Task LoadImageAsync(object scheduledObject, Size size) { try { bool raiseEvent; // Does the ImageFrame contain no previously rendered image? if (_imageSurface == null) { // Since a new object is being loaded, ImageOpened event // must be raised on successful load raiseEvent = true; // Show the placeholder, if required DisplayPlaceHolder(); // Create the ImageSurface and get the uri of the cached object var cachedUri = await LoadNextScheduledObject(scheduledObject, size, false); // Object was successfully cached and loaded if ((cachedUri != null) && (_imageSurface != null)) { // Set initial opacity to 0 so that the contentVisual can be faded in _frameContentVisual.Opacity = 0; // Apply the surfaceBrush to the visual var surfaceBrush = _compositor.CreateSurfaceBrush(_imageSurface.Surface); // Update the surface brush based on the Stretch and Alignment options surfaceBrush.UpdateSurfaceBrushOptions(Stretch, AlignX, AlignY); _frameContentVisual.Brush = surfaceBrush; // Report 100% progress ProgressHandler(100); // Hide the placeholder HidePlaceholder(); // If we are rendering fast, no need to animate if (RenderFast) { _frameContentVisual.Opacity = 1; } else { // Start transition animation StartTransition(true); } } // Caching or Loading of the object failed else { // Clear the existing image ClearImageFrame(); } } else { var hashedUri = await ImageCache.GetHashedUriAsync(scheduledObject); // Check whether the object to load is same as the existing image // loaded in the ImageSurface if (_imageSurface.Uri.IsEqualTo(hashedUri)) { // Since the Uri has not changed, no need to raise the ImageOpened event // Just resize the ImageSurface with the given imageOptions and // update the frameContentVisual's brush raiseEvent = false; _imageSurface.Resize(size, _imageOptions); // Update the surface brush based on the Stretch and Alignment options if (RenderFast) { // Use no animations to update alignment if we are rendering fast (_frameContentVisual.Brush as CompositionSurfaceBrush)?.UpdateSurfaceBrushOptions(Stretch, AlignX, AlignY); } else { // Update stretch and alignment using animation (_frameContentVisual.Brush as CompositionSurfaceBrush)?.UpdateSurfaceBrushOptions(Stretch, AlignX, AlignY, _alignXAnimation, _alignYAnimation); } } else { // Since a different Uri is being loaded, then ImageOpened event // must be raised on successful load raiseEvent = true; // Show the placeholder, if required DisplayPlaceHolder(); // Create a temporary visual which loads the new Uri _nextVisualContent.Opacity = 0; // Load the object scheduled for load var cachedUri = await LoadNextScheduledObject(scheduledObject, size, true); // Object was successfully cached and loaded if (cachedUri != null) { // Create the surface brush for the next image _nextSurfaceBrush = _compositor.CreateSurfaceBrush(_nextImageSurface.Surface); // Update the surface brush based on the Stretch and Alignment options _nextSurfaceBrush.UpdateSurfaceBrushOptions(Stretch, AlignX, AlignY); _nextVisualContent.Brush = _nextSurfaceBrush; // Report 100% progress ProgressHandler(100); // If we are rendering fast, then no need to animate. if (RenderFast) { _frameContentVisual.Opacity = 0; _nextVisualContent.Opacity = 1; // apply the new brush to the frameVisualContent _frameContentVisual.Brush = _nextSurfaceBrush; // Update the surface image _imageSurface = _nextImageSurface; // Make the frameVisualContent visible again _frameContentVisual.Opacity = 1; // Hide the placeholder HidePlaceholder(); // Hide the nextVisualContent _nextVisualContent.Opacity = 0; } else { _compositor.CreateScopedBatch(CompositionBatchTypes.Animation, () => { // Start transition animation StartTransition(false); }, () => { // apply the new brush to the frameVisualContent _frameContentVisual.Brush = _nextSurfaceBrush; // Update the surface image _imageSurface = _nextImageSurface; // Make the frameVisualContent visible again _frameContentVisual.Opacity = 1; // Hide the placeholder HidePlaceholder(); // Hide the nextVisualContent _nextVisualContent.Opacity = 0; }); } } // Caching or Loading of the object failed else { // Clear the existing image ClearImageFrame(); } } } if (raiseEvent) { // Notify to subscribers that the image has been successfully loaded await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ImageOpened?.Invoke(this, new ImageFrameEventArgs(_imageSurface.Uri, string.Empty)); }); } } catch (IOException ex) { // Notify to subscribers that loading of the image failed await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ImageFailed?.Invoke(this, new ImageFrameEventArgs(_currentObject, ex.ToString())); }); } // Update the engineState after load is completed PostLoadImage(); }
/// <summary> /// Creates the circle used in the circle brush if not already created. /// </summary> private void EnsureCircleBrush() { if (_circleBrush == null) { _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor); _circleSurface = _imageLoader.CreateCircleSurface(200, Colors.White); _circleBrush = _compositor.CreateSurfaceBrush(_circleSurface.Surface); } }
/// <summary> /// Disposes the resources /// </summary> public void Dispose() { // Clean up resources _compositor = null; Source = null; DataContext = null; Foreground = null; Background = null; _scheduledObject = null; _currentObject = null; // Clean up Composition Objects _imageSurface?.Dispose(); _imageSurface = null; _nextImageSurface?.Dispose(); _nextImageSurface = null; _frameLayerMask?.Dispose(); _frameLayerMask = null; _placeholderContentMask?.Dispose(); _placeholderContentMask = null; _placeholderContentBrush?.Dispose(); _placeholderContentBrush = null; _nextSurfaceBrush?.Dispose(); _nextSurfaceBrush = null; _rootContainer?.Dispose(); _rootContainer = null; _shadowVisual?.Dispose(); _shadowVisual = null; _frameLayer?.Dispose(); _frameLayer = null; _frameBackgroundVisual?.Dispose(); _frameBackgroundVisual = null; _placeholderBackgroundVisual?.Dispose(); _placeholderBackgroundVisual = null; _placeholderContentVisual?.Dispose(); _placeholderContentVisual = null; _frameContentVisual?.Dispose(); _frameContentVisual = null; _nextVisualContent?.Dispose(); _nextVisualContent = null; _shadow?.Dispose(); _shadow = null; _layerEffectBrush?.Dispose(); _layerEffectBrush = null; _imageOptions = null; _zoomInAnimationGroup?.Dispose(); _zoomInAnimationGroup = null; _fadeOutAnimation?.Dispose(); _fadeOutAnimation = null; _fadeInAnimation?.Dispose(); _fadeInAnimation = null; _colorAnimation?.Dispose(); _colorAnimation = null; _alignXAnimation?.Dispose(); _alignXAnimation = null; _alignYAnimation?.Dispose(); _alignYAnimation = null; _offsetAnimation?.Dispose(); _offsetAnimation = null; _scaleAnimation?.Dispose(); _scaleAnimation = null; // Dispose the generator at the end to allow the // dependant composition objects to unsubscribe from // generator events _generator?.Dispose(); _generator = null; }