Saltar al contenido

Agregar fondo degradado a diseños en Xamarin Forms visual studio

Ya no tienes que buscar más en internet ya que estás al espacio justo, poseemos la respuesta que buscas sin problema.

Solución:

En el siguiente código, podemos configurar el degradado horizontal y vertical (lo puse en # región) para cualquier diseño que escribo a continuación para StackLayout si desea escribir otro diseño, simplemente reemplace su diseño en StackLayout.

En PCL:

using System;
using Xamarin.Forms;

namespace GradientColor
 
   public class GradientColorStack : StackLayout
    
      public Color StartColor  get; set; 
      public Color EndColor  get; set; 
    
 

Xamarin.Android:

  using System;
  using GradientColor;
  using GradientColor.Droid;
  using Xamarin.Forms;
  using Xamarin.Forms.Platform.Android;
  [assembly: ExportRenderer(typeof(GradientColorStack), typeof(GradientColorStackRenderer))]

 namespace GradientColor.Droid
  
     public class GradientColorStackRenderer : VisualElementRenderer
       
    private Color StartColor  get; set; 
    private Color EndColor  get; set; 

    protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)
      
        #region for Vertical Gradient
        //var gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height,
        #endregion

        #region for Horizontal Gradient
     var gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0,
          #endregion

            this.StartColor.ToAndroid(),
            this.EndColor.ToAndroid(),
            Android.Graphics.Shader.TileMode.Mirror);

        var paint = new Android.Graphics.Paint()
        
            Dither = true,
        ;
        paint.SetShader(gradient);
        canvas.DrawPaint(paint);
        base.DispatchDraw(canvas);
    

    protected override void OnElementChanged(ElementChangedEventArgs e)
    
   

Xamarin.iOS:

  using System;
  using CoreAnimation;
  using CoreGraphics;
  using GradientColor;
  using GradientColor.iOS;
  using Xamarin.Forms;
  using Xamarin.Forms.Platform.iOS;
  [assembly: ExportRenderer(typeof(GradientColorStack), typeof(GradientColorStackRenderer))]

 namespace GradientColor.iOS
   
public class GradientColorStackRenderer : VisualElementRenderer
    
      public override void Draw(CGRect rect)
      
        base.Draw(rect);
        GradientColorStack stack = (GradientColorStack)this.Element;
        CGColor startColor = stack.StartColor.ToCGColor();

        CGColor endColor = stack.EndColor.ToCGColor();

        #region for Vertical Gradient

        var gradientLayer = new CAGradientLayer();

        #endregion

        #region for Horizontal Gradient

        //var gradientLayer = new CAGradientLayer()
        //
        //  StartPoint = new CGPoint(0, 0.5),
        //  EndPoint = new CGPoint(1, 0.5)
        //;

        #endregion



        gradientLayer.Frame = rect;
        gradientLayer.Colors = new CGColor[]  startColor, endColor 
        ;

        NativeView.Layer.InsertSublayer(gradientLayer, 0);
      
    
 

En XAML:

 
 
 
    
        
        
    
    
         
            
    
    
         
               
               

         
     
   
  

Para aquellos que quieren un gradiente con todas las funciones en las aplicaciones de Xamarin.Forms, está mi código:

En tu PCL

GradientLayout.cs

using Xamarin.Forms;

namespace MyProject.Renderers

    public class GradientLayout : StackLayout
    
        public string ColorsList  get; set; 

        public Color[] Colors
        
            get
            
                string[] hex = ColorsList.Split(',');
                Color[] colors = new Color[hex.Length];

                for (int i = 0; i < hex.Length; i++)
                
                    colors[i] = Color.FromHex(hex[i].Trim());
                

                return colors;
            
        

        public GradientColorStackMode Mode  get; set; 
    

GradientColorStackMode.cs

namespace MyProject.Renderers

    public enum GradientColorStackMode
    
        ToRight,
        ToLeft,
        ToTop,
        ToBottom,
        ToTopLeft,
        ToTopRight,
        ToBottomLeft,
        ToBottomRight
    

En tu proyecto de iOS

GradientLayoutRenderer.cs

using CoreAnimation;
using CoreGraphics;
using MyProject.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(GradientLayout), typeof(GradientLayoutRenderer))]

namespace MyProject.iOS.Renderers

    public class GradientLayoutRenderer : VisualElementRenderer
    
        public override void Draw(CGRect rect)
        
            base.Draw(rect);
            GradientLayout layout = (GradientLayout)Element;

            CGColor[] colors = new CGColor[layout.Colors.Length];

            for (int i = 0, l = colors.Length; i < l; i++)
            
                colors[i] = layout.Colors[i].ToCGColor();
            

            var gradientLayer = new CAGradientLayer();

            switch (layout.Mode)
            
                default:
                case GradientColorStackMode.ToRight:
                    gradientLayer.StartPoint = new CGPoint(0, 0.5);
                    gradientLayer.EndPoint = new CGPoint(1, 0.5);
                    break;
                case GradientColorStackMode.ToLeft:
                    gradientLayer.StartPoint = new CGPoint(1, 0.5);
                    gradientLayer.EndPoint = new CGPoint(0, 0.5);
                    break;
                case GradientColorStackMode.ToTop:
                    gradientLayer.StartPoint = new CGPoint(0.5, 0);
                    gradientLayer.EndPoint = new CGPoint(0.5, 1);
                    break;
                case GradientColorStackMode.ToBottom:
                    gradientLayer.StartPoint = new CGPoint(0.5, 1);
                    gradientLayer.EndPoint = new CGPoint(0.5, 0);
                    break;
                case GradientColorStackMode.ToTopLeft:
                    gradientLayer.StartPoint = new CGPoint(1, 0);
                    gradientLayer.EndPoint = new CGPoint(0, 1);
                    break;
                case GradientColorStackMode.ToTopRight:
                    gradientLayer.StartPoint = new CGPoint(0, 1);
                    gradientLayer.EndPoint = new CGPoint(1, 0);
                    break;
                case GradientColorStackMode.ToBottomLeft:
                    gradientLayer.StartPoint = new CGPoint(1, 1);
                    gradientLayer.EndPoint = new CGPoint(0, 0);
                    break;
                case GradientColorStackMode.ToBottomRight:
                    gradientLayer.StartPoint = new CGPoint(0, 0);
                    gradientLayer.EndPoint = new CGPoint(1, 1);
                    break;
            

            gradientLayer.Frame = rect;
            gradientLayer.Colors = colors;

            NativeView.Layer.InsertSublayer(gradientLayer, 0);
        
    

En tu proyecto de Android

GradientLayoutRenderer.cs

using System;
using Android.Content;
using MyProject.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(GradientLayout), typeof(GradientLayoutRenderer))]

namespace MyProject.Droid.Renderers

    public class GradientLayoutRenderer : VisualElementRenderer
    
        private Color[] Colors  get; set; 

        private GradientColorStackMode Mode  get; set; 

        public GradientLayoutRenderer(Context ctx) : base(ctx)
         

        protected override void DispatchDraw(global::Android.Graphics.Canvas canvas)
        
            Android.Graphics.LinearGradient gradient;

            int[] colors = new int[Colors.Length];

            for (int i = 0, l = Colors.Length; i < l; i++)
            
                colors[i] = Colors[i].ToAndroid().ToArgb();
            

            switch (Mode)
            
                default:
                case GradientColorStackMode.ToRight:
                    gradient = new Android.Graphics.LinearGradient(0, 0, Width, 0, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToLeft:
                    gradient = new Android.Graphics.LinearGradient(Width, 0, 0, 0, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToTop:
                    gradient = new Android.Graphics.LinearGradient(0, Height, 0, 0, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToBottom:
                   gradient = new Android.Graphics.LinearGradient(0, 0, 0, Height, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToTopLeft:
                    gradient = new Android.Graphics.LinearGradient(Width, Height, 0, 0, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToTopRight:
                    gradient = new Android.Graphics.LinearGradient(0, Height, Width, 0, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToBottomLeft:
                    gradient = new Android.Graphics.LinearGradient(Width, 0, 0, Height, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
                case GradientColorStackMode.ToBottomRight:
                    gradient = new Android.Graphics.LinearGradient(0, 0, Width, Height, colors, null, Android.Graphics.Shader.TileMode.Mirror);
                    break;
            

            var paint = new Android.Graphics.Paint()
            
                Dither = true,
            ;

            paint.SetShader(gradient);
            canvas.DrawPaint(paint);

            base.DispatchDraw(canvas);
        

        protected override void OnElementChanged(ElementChangedEventArgs e)
        
    

En el proyecto UWP

GradientLayoutRenderer.cs

using System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using MyProject.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using Point = Windows.Foundation.Point;

[assembly: ExportRenderer(typeof(GradientLayout), typeof(GradientLayoutRenderer))]

namespace MyProject.UWP.Renderers

    public class GradientLayoutRenderer : VisualElementRenderer
    
        private Color[] Colors  get; set; 

        private GradientColorStackMode Mode  get; set; 

        protected override void UpdateBackgroundColor()
        
            base.UpdateBackgroundColor();

            LinearGradientBrush gradient;

            GradientStopCollection stopCollection = new GradientStopCollection();

            for (int i = 0, l = Colors.Length; i < l; i++)
            
                stopCollection.Add(new GradientStop
                
                    Color = Windows.UI.Color.FromArgb((byte)(Colors[i].A * byte.MaxValue), (byte)(Colors[i].R * byte.MaxValue), (byte)(Colors[i].G * byte.MaxValue), (byte)(Colors[i].B * byte.MaxValue)),
                    Offset = (double)i / Colors.Length
                );
            

            switch (Mode)
            
                default:
                case GradientColorStackMode.ToRight:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(0, 0.5),
                        EndPoint = new Point(1, 0.5)
                    ;
                    break;
                case GradientColorStackMode.ToLeft:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(1, 0.5),
                        EndPoint = new Point(0, 0.5)
                    ;
                    break;
                case GradientColorStackMode.ToTop:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(0.5, 1),
                        EndPoint = new Point(0.5, 0)
                    ;
                    break;
                case GradientColorStackMode.ToBottom:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(0.5, 0),
                        EndPoint = new Point(0.5, 1)
                    ;
                    break;
                case GradientColorStackMode.ToTopLeft:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(1, 1),
                        EndPoint = new Point(0, 0)
                    ;
                    break;
                case GradientColorStackMode.ToTopRight:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(0, 1),
                        EndPoint = new Point(1, 0)
                    ;
                    break;
                case GradientColorStackMode.ToBottomLeft:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(1, 0),
                        EndPoint = new Point(0, 1)
                    ;
                    break;
                case GradientColorStackMode.ToBottomRight:
                    gradient = new LinearGradientBrush
                    
                        GradientStops = stopCollection,
                        StartPoint = new Point(0, 0),
                        EndPoint = new Point(1, 1)
                    ;
                    break;
            

            Background = gradient;
        

        protected override void OnElementChanged(ElementChangedEventArgs e)
        
    

En tus páginas XAML



    


¡Espero que esto ayude!

Agregue SkiaSharp Nuget a su proyecto junto con esta clase. Úselo en su xaml donde sea que necesite un degradado.

public partial class GradientView : ContentView
{
    public Color StartColor  get; set;  = Color.Transparent;
    public Color EndColor  get; set;  = Color.Transparent;
    public bool Horizontal  get; set;  = false;

    public GradientView()
    
        InitializeComponent();

        SKCanvasView canvasView = new SKCanvasView();
        canvasView.PaintSurface += OnCanvasViewPaintSurface;
        Content = canvasView;
    

    void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
    
        SKImageInfo info = args.Info;
        SKSurface surface = args.Surface;
        SKCanvas canvas = surface.Canvas;

        canvas.Clear();

        var colors = new SKColor[]  StartColor.ToSKColor(), EndColor.ToSKColor();
        SKPoint startPoint = new SKPoint(0,0);
        SKPoint endPoint = Horizontal ? new SKPoint(info.Width, 0) : new SKPoint(0, info.Height);

        var shader = SKShader.CreateLinearGradient(startPoint, endPoint, colors, null, SKShaderTileMode.Clamp);

        SKPaint paint = new SKPaint
        
            Style = SKPaintStyle.Fill,
            Shader = shader
        ;

        canvas.DrawRect(new SKRect(0, 0, info.Width, info.Height), paint);
    

Finalizando este artículo puedes encontrar los informes de otros programadores, tú de igual forma eres capaz dejar el tuyo si te apetece.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *