MAUI中基于字符串绑定SkiaSharp动画不显示的问题排查
问题分析与解决方法
1. 先检查资源的打包配置
首先确认Resources/Raw下的动画JSON文件(比如night_raining.json)的生成操作和复制设置:
- 右键文件 → 属性 → 生成操作选择
MauiAsset,复制到输出目录选择如果较新则复制
如果资源没被正确打包进应用,哪怕绑定路径正确也加载不到动画。
2. 修正Source的绑定方式
SKLottieView的Source属性不能像图片那样直接绑定文件名字符串,它需要的是SKData或正确的资源流引用,以下两种方法都能解决:
方法一:用绑定转换器转成资源流
先写一个转换器,把文件名转换成SKLottie能识别的资源数据:
public class LottieResourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string fileName && !string.IsNullOrEmpty(fileName)) { using var stream = FileSystem.OpenAppPackageFileAsync(fileName).Result; return SKData.Create(stream); } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
然后在XAML里引用转换器并修改绑定:
<!-- 先在页面资源里声明转换器 --> <ContentPage.Resources> <local:LottieResourceConverter x:Key="LottieResourceConverter" /> </ContentPage.Resources> <!-- 修改SKLottieView的绑定 --> <skia:SKLottieView Source="{Binding CurrentWeather, Converter={StaticResource LottieResourceConverter}}" RepeatCount="-1" HeightRequest="300" WidthRequest="200" HorizontalOptions="Center" />
方法二:在ViewModel里直接处理成SKData
如果不想用转换器,可以直接在ViewModel里把文件名转成SKData属性:
[ObservableProperty] private SKData _currentWeatherLottie; public YourCurrentLocationForecast(WeatherService weatherService, IConnectivity connectivity, IGeolocation geolocation) { this.weatherService = weatherService; this.connectivity = connectivity; this.geolocation = geolocation; title = "Weather"; LoadLottie("night_raining.json"); TestingTheDailyStatMethod(); } private void LoadLottie(string fileName) { using var stream = FileSystem.OpenAppPackageFileAsync(fileName).Result; CurrentWeatherLottie = SKData.Create(stream); }
然后XAML绑定改成:
<skia:SKLottieView Source="{Binding CurrentWeatherLottie}" RepeatCount="-1" HeightRequest="300" WidthRequest="200" HorizontalOptions="Center" />
3. 确认绑定上下文是否正确
检查页面的BindingContext是否已经设置为YourCurrentLocationForecast的实例:
比如在页面构造函数里:
public WeatherPage() { InitializeComponent(); BindingContext = new YourCurrentLocationForecast(/* 对应服务实例 */); }
如果绑定上下文没设对,ViewModel的属性根本传不到控件上。
4. 快速测试排查
可以先在XAML里硬编码Source,看看动画能不能加载:
<skia:SKLottieView Source="night_raining.json" RepeatCount="-1" HeightRequest="300" WidthRequest="200" HorizontalOptions="Center" />
如果这样也加载失败,要么是资源配置错了,要么是文件名大小写不对(Android/iOS对文件名大小写敏感)。
内容的提问来源于stack exchange,提问作者Lass
相关产品推荐
相关产品推荐

