Xamarin.Essentials截图功能在Android10设备上运行报类型加载异常
Xamarin.Essentials截图功能在Android 10设备上触发TypeLoadException问题排查
- 业务实现逻辑:按钮点击事件中获取设备截图,将截图内容读取到内存流后,把流设置为名为
imagetest的图片控件的图片源 - 当前开发环境:使用最新版本的Xamarin.Essentials与Xamarin.Forms,测试设备为Android 10
- 异常现象:触发按钮点击执行截图逻辑时,系统抛出类型加载失败异常
当前截图方法实现代码
private async void CaptureScreenshot(object sender, EventArgs e) { var screenshot = await Screenshot.CaptureAsync(); var stream = await screenshot.OpenReadAsync(); var array_image = ImageSource.FromStream(() => stream); imagetest.Source = array_image; }
完整报错信息
System.TypeLoadException Message=Could not load type of field 'Order_Form_V1.CustomArrayConfiguration+d__3:5__2' (6) due to: Could not resolve type with token 01000029 from typeref (expected class 'Xamarin.Essentials.ScreenshotResult' in assembly 'Xamarin.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null') assembly:Xamarin.Essentials, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null type:Xamarin.Essentials.ScreenshotResult member:(null)
排查方向与解决建议
- 核对全项目Xamarin.Essentials版本一致性:共享项目、Android平台项目、iOS平台项目的Xamarin.Essentials NuGet包版本必须完全统一,若存在平台项目引用旧版本、共享项目引用新版本的错配情况,旧版本程序集内不存在
ScreenshotResult公开类型,会直接触发类型解析失败的异常 - 清理编译缓存后全量重编译:删除解决方案目录下所有
bin、obj文件夹,重新执行NuGet包还原后生成项目,避免旧版本程序集残留被打包进安装包,导致运行时找不到目标类型 - 调整流绑定逻辑:当前代码中
OpenReadAsync返回的是一次性封装的只读流,跨异步上下文传递时容易出现流位置偏移,导致图片绑定失败,可参考优化代码:private async void CaptureScreenshot(object sender, EventArgs e) { var screenshot = await Screenshot.CaptureAsync(); var stream = await screenshot.OpenReadAsync(); imagetest.Source = ImageSource.FromStream(() => { stream.Position = 0; return stream; }); } - 检查Android项目版本配置:截图能力要求Android项目的目标编译版本设置为Android 10(API 29)及以上,若目标编译版本低于该值,Xamarin.Essentials的平台实现会被自动裁剪,对应类型会在编译阶段被移除
- 调整链接器裁剪规则:若项目启用了全程序集链接模式,需要为Xamarin.Essentials相关类型添加保留规则,避免
ScreenshotResult被链接器裁剪移除。可在Android项目中添加LinkDescription.xml配置文件,将生成操作设置为LinkDescription,添加保留规则:<assembly fullname="Xamarin.Essentials"> <type fullname="Xamarin.Essentials.ScreenshotResult" preserve="all"/> </assembly>
内容的提问来源于stack exchange,提问作者loganwenzel
相关产品推荐
相关产品推荐

