如何在UWP中将Grid.Background设置为MediaPlayer?

时间:2018-12-12 09:11:58

标签: mobile uwp windows-phone uwp-xaml

如何在UWP应用中将视频添加到Grid.Background

在以前的版本中,我使用

<Grid.Background>
    <ImageBrush ImageSource="ms-appx:///Assets/carosel3.jpg" Stretch="UniformToFill"/>
</Grid.Background>

1 个答案:

答案 0 :(得分:0)

有两种方法可以在UWP中完成此操作。

合成API

Composition API提供CompositionSurfaceBrush,您可以使用它们通过MediaPlayer用视频绘制的像素绘制区域。 documentation中的示例:

Compositor _compositor = ElementCompositionPreview.GetElementVisual(MyGrid).Compositor;
SpriteVisual _videoVisual;
CompositionSurfaceBrush _videoBrush;

// MediaPlayer set up with a create from URI

_mediaPlayer = new MediaPlayer();

// Get a source from a URI. This could also be from a file via a picker or a stream
var source = MediaSource.CreateFromUri(new Uri("https://www.example.com/video.mp4"));
var item = new MediaPlaybackItem(source);
_mediaPlayer.Source = item;
_mediaPlayer.IsLoopingEnabled = true;

// Get the surface from MediaPlayer and put it on a brush
_videoSurface = _mediaPlayer.GetSurface(_compositor);
_videoBrush = _compositor.CreateSurfaceBrush(_videoSurface.CompositionSurface);

_videoVisual = _compositor.CreateSpriteVisual();
_videoVisual.Brush = _videoBrush;

有关更多信息,请查阅文档,以查找有关在互联网上使用Composition API(例如here)的众多教程之一。

单独的`MediaPlayer元素

一个更简单的解决方案是将MediaPlayerElement放在Grid本身下面。当Grid具有Transparent背景时,视频将显示在Grid下方。

<Grid>
    <MediaPlayerElement x:Name="mediaPlayer"
                      AreTransportControlsEnabled="False"
                      Source="ms-appx:///SomeVideo.mp4" />
    <Grid>
       ... your content
    </Grid>
</Grid>