You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin CommunityToolkit竖屏录制视频被旋转90度如何解决

问题根因

你使用的Xamarin.CommunityToolkit 1.2.0版本存在已知的CameraView视频录制缺陷:安卓端录制视频时不会自动写入和设备方向匹配的旋转元数据,导致导出的视频默认被识别为横屏,出现90度旋转的问题,且该版本MediaCapturedEventArgs.Rotation属性未正确赋值,始终返回0。


解决方法

方案1:升级Xamarin CommunityToolkit版本(优先选择)

1.2.0属于非常早期的预览版本,后续的XCT稳定版已经修复了视频旋转元数据自动写入的问题,升级到1.3.0及以上的稳定版后,录制的视频会自动携带对应方向的旋转标签,绝大多数播放器都可以自动识别方向,不需要额外代码处理。

方案2:不升级版本时通过依赖服务修正旋转元数据

如果因为项目兼容原因无法升级XCT,可以通过平台特定的依赖服务给生成的视频写入正确的旋转标签,步骤如下:

  1. 共享项目定义接口
public interface IVideoRotationFixer
{
    // videoPath为视频保存的绝对路径,rotationDegree为需要修正的角度,竖屏后置摄像头默认填90
    void SetVideoRotation(string videoPath, int rotationDegree);
}
  1. 监听设备方向获取正确旋转角度
    在CameraPage中添加全局变量存储当前需要修正的角度:
// 后置摄像头竖屏录制对应旋转90度,横屏可根据设备方向动态修改为0/180/270
private int _currentRotation = 90;

可通过Xamarin.Essentials.DeviceDisplay.Orientation事件监听方向变化,动态更新_currentRotation的值。
3. 安卓端实现接口写入旋转元数据
在安卓项目中添加接口实现:

[assembly: Dependency(typeof(VideoRotationFixer_Android))]
namespace YOUR_APP_NAMESPACE.Droid
{
    public class VideoRotationFixer_Android : IVideoRotationFixer
    {
        public void SetVideoRotation(string videoPath, int rotationDegree)
        {
            using var exif = new Android.Media.ExifInterface(videoPath);
            exif.SetAttribute(Android.Media.ExifInterface.TagOrientation, rotationDegree.ToString());
            exif.SaveAttributes();
        }
    }
}
  1. 保存视频时调用修正逻辑
    修改CameraView_MediaCaptured中的视频保存逻辑,注意需要让你的exportFileMediaSource方法返回视频保存的绝对路径:
case CameraCaptureMode.Video:
    FileMediaSource file = e.Video.File;
    // 修改exportFileMediaSource返回保存后的绝对路径
    string savePath = DependencyService.Get<IStorage>().exportFileMediaSource(file, "asd.mp4");
    // 调用旋转修正
    DependencyService.Get<IVideoRotationFixer>().SetVideoRotation(savePath, _currentRotation);
    doCameraThings.Text = "Registra";
    DependencyService.Get<IToast>().ShortAlert("Video salvato");
    break;

如果需要兼容所有不识别元数据的播放器,可以集成Xamarin.FFmpeg库对视频进行重编码旋转,调用命令为-i 输入路径 -vf "transpose=1" 输出路径,transpose=1对应顺时针旋转90度。

方案3:固定页面方向(仅适用于只需要竖屏录制的场景)

如果你的录制页面只允许竖屏使用,可以直接锁定页面方向避免旋转问题,在CameraPage中添加如下代码:

protected override void OnAppearing()
{
    base.OnAppearing();
    // 锁定竖屏
    Xamarin.Essentials.DeviceDisplay.LockRotation(Xamarin.Essentials.DisplayRotation.Portrait);
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    // 离开页面时解锁方向
    Xamarin.Essentials.DeviceDisplay.UnlockRotation();
}

内容的提问来源于stack exchange,提问作者blacky99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:09:00