简体   繁体   中英

Xamarin.Forms SkiaSharp Gradient working on Android but not on iOS

We need a Gradient on our pages, so we're using SkiaSharp and a GradientView. This works fine on Android but isn't working on iOS - the Gradient just doesn't display.

Do we need to do any iOS-specific initialisation for SkiaSharp on iOS, with renderers or code in the AppDelegate?

Edit This is running on an iPad with iOS 10.3.3. Our XAML:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="MyProject.XForms.Controls.GradientView">
    </ContentView>

Our XAML.cs

using SkiaSharp;
using SkiaSharp.Views.Forms;
using Xamarin.Forms;

namespace MyProject.XForms.Controls
{
    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);
        }
    }
}

I ran into the same problem and read the documentation. It says you need to tell the canvas to update. You do this using the following line of code:

 canvasView.InvalidateSurface(); 

Maybe you haven't installed the NuGets (both SkiaSharp and SkiaSharp.Views.Forms) into the iOS project?

I copy-pasted your code into a brand new app, and it worked first time.

Some other things that may be the issue is that the view height/width is 0. Or, the dodgy case where the color is transparent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM