Example #1
0
        public static void UpdateBackground(this NSView control, Brush brush)
        {
            if (control == null)
            {
                return;
            }

            NSView view = ShouldUseParentView(control) ? control.Superview : control;

            // Clear previous background color
            if (control.Layer != null && control.Layer.Name == SolidColorBrushLayer)
            {
                control.Layer.BackgroundColor = NSColor.Clear.CGColor;
            }

            // Remove previous background gradient layer if any
            RemoveBackgroundLayer(view);

            if (Brush.IsNullOrEmpty(brush))
            {
                return;
            }

            control.WantsLayer = true;
            control.LayerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.BeforeViewResize;

            if (brush is SolidColorBrush solidColorBrush)
            {
                control.Layer.Name = SolidColorBrushLayer;

                var backgroundColor = solidColorBrush.Color;

                if (backgroundColor == Color.Default)
                {
                    control.Layer.BackgroundColor = NSColor.Clear.CGColor;
                }
                else
                {
                    control.Layer.BackgroundColor = backgroundColor.ToCGColor();
                }
            }
            else
            {
                var backgroundLayer = GetBackgroundLayer(control, brush);

                if (backgroundLayer != null)
                {
                    view.InsertBackgroundLayer(backgroundLayer, 0);
                }
            }
        }