Revision Difference
style-video#562834
<cat>UI.Styles</cat>
<title>Video Backgrounds</title>
# Video Backgrounds
To play a video in the background of a panel, set the background-image property to the path of an MP4 or WebM file.
```
MyVideoPanel {
// This path is relative to the Assets folder of your project.
background-image: url("ui/video/my_video.mp4");
}
```
To allow a video of any aspect ratio to fit snugly within the panel, set these properties like so:
```
background-size: contain;
background-position: center;
background-repeat: no-repeat;
```
The video will play once the panel is created. No audio will play, and the video will loop whenever it reaches the end.
<note>
The playback progress of background-image videos will persist between rebuilds of the UI, only restarting once the underlying VideoPlayer is garbage collected.
</note>
# Using a VideoPlayer Texture
For more control over video playback and audio, you'll need to set the background image of the panel to the texture of a VideoPlayer that you control.
```cs
using Sandbox.UI;
public partial class VideoPlayerPanel : Panel
{
public bool ShouldLoop { get; set; } = true;
private VideoPlayer _player;
public VideoPlayerPanel()
protected override void OnAfterTreeRender( bool firstTime )
{
_player = new VideoPlayer();
if ( !firstTime )
return;⤶
⤶
_player = new VideoPlayer();⤶
// When this video plays, its audio will also automatically play.
_player.Play( FileSystem.Mounted, "ui/video/my_video.mp4" );
// Set the background-image property of the style to the VideoPlayer's Texture.
Style.SetBackgroundImage( _player.Texture );
// Pause or unpause the video when this panel is clicked.
AddEventListener( "onclick", _ => _player?.TogglePause() );
}
public override void Tick()
{
if ( _player is null )
return;
// The VideoPlayer texture will not update unless Present is called.
_player.Present();
// Loop when the video concludes.
if ( ShouldLoop && _player.PlaybackTime >= _player.Duration )
{
_player.Seek( 0f );
}
}
}
```