- Home /
RawImage with correct aspect ratio
I'am using a RawImage + VideoPlayer to display multiple Videos on UI elements (for iOS/Android targets). But all Videos are getting streched into the RawImage rectangle, loosing its aspect ratio. How to play different videos with correct aspect ratio in a RawImage?
Thank you
Comment
Best Answer
Answer by trnq1ll0 · Dec 02, 2019 at 02:37 PM
Thank you @asd234w4r5 for your answer. After a lot of research and T&E, here is my full solution:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
public class Video2RawImage : MonoBehaviour
{
public VideoPlayer videoPlayer;
public RawImage rawImage;
private int rawImageOriginWidth;
private int rawImageOriginHeight;
public void Start()
{
RectTransform rt = rawImage.GetComponent<RectTransform>();
// get the rect size as base size for the upcomming video
rawImageOriginWidth = Mathf.RoundToInt(rt.rect.width);
rawImageOriginHeight = Mathf.RoundToInt(rt.rect.height);
StartCoroutine(PlayVideo());
}
IEnumerator PlayVideo()
{
videoPlayer.playOnAwake = false;
videoPlayer.Prepare();
while (!videoPlayer.isPrepared) {
Debug.Log("Preparing Video");
yield return null;
}
rawImage.texture = videoPlayer.texture;
int[] scaledVideo;
if (videoPlayer.source == VideoSource.VideoClip){
scaledVideo = scaleResolution((int) videoPlayer.clip.width, (int) videoPlayer.clip.height, rawImageOriginWidth, rawImageOriginHeight);
}
else {
Texture vidTex = videoPlayer.texture;
scaledVideo = scaleResolution(vidTex.width, vidTex.height, rawImageOriginWidth, rawImageOriginHeight);
}
rawImage.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, scaledVideo[0]);
rawImage.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, scaledVideo[1]);
videoPlayer.Play();
}
int[] scaleResolution(int width, int heigth, int maxWidth, int maxHeight)
{
int new_width = width;
int new_height = heigth;
if (width > heigth){
new_width = maxWidth;
new_height = (new_width * heigth) / width;
}
else
{
new_height = maxHeight;
new_width = (new_height * width) / heigth;
}
int[] dimension = { new_width, new_height };
return dimension;
}
}
Answer by WheresMommy · Nov 29, 2019 at 11:14 AM
I did this with creating a rawimage on runtime and having this created with the videos pixelsize or aspect ratio. There is also an aspect ratio component for Unity UI, which you can feed to resize your UI Elements.