• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Jason-RT-Bond · Mar 26, 2012 at 02:54 PM · androidiphonewebcamaspect-ratio

How Can I Get the Device Camera Aspect Ratio?

I've been using the WebCamTexture class to implement device camera views on mobile devices (both iPhones and Androids). However, I've noticed that the aspect ratio of the camera on a device does not necessarily match the aspect ratio of the screen (esp. on the wide-screen Androids). I can force the aspect to be 4:3 (which suits MOST cases), but what if the device's camera uses something different?

I can't find any information in WebCamTexture or WebCamDevice to help get the appropriate aspect ratio. Can anyone help?

Comment
jellybit
Fattie
Novack
vexe
Exceptione
jijieciprian

People who like this

6 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

  • Sort: 
avatar image
Best Answer

Answer by Fattie · Apr 16, 2014 at 10:54 AM

Here's the state of the art solution for 2016:

http://answers.unity3d.com/questions/773464/webcamtexture-correct-resolution-and-ratio.html#answer-1148424

http://answers.unity3d.com/questions/909967/getting-a-web-cam-to-play-on-ui-texture-image.html

Hope it helps someone!

Comment
Jason-RT-Bond
bombsquare
Exceptione
jijieciprian

People who like this

4 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jason-RT-Bond · Apr 16, 2014 at 03:11 PM 2
Share

Thanks, Fattie! Most helpful.

It's too bad this seems to be a very low-priority for Unity. It's really useful for augmented reality applications, but Unity Tech seems to favour AAA game features.

avatar image

Answer by Jason-RT-Bond · Feb 08, 2013 at 11:41 PM

This is quite belated, but I was prepping a test project to submit with a bug report, and discovered a solution.

Following what rutter suggested, you can indeed request a high resolution and framerate, and will generally get the best available (e.g ask for 1080p at 60fps and you'll get 720p at 30fps). This is NOT ideal by any means, but it gets you something. The problem then is with the "16x16" size Unity seems to report for the camera texture, as mentioned by BTamas. This is what Unity gives back on an iPad even with the latest version (4.0.1) after requesting Play on the camera texture. With these (incorrect) numbers it seems impossible to set the dimensions correctly.

HOWEVER, the cause of this seems to be that starting the camera is asynchronous. By constantly checking them after starting the camera, I found that I would soon get correct values across all my devices (iPads 2, 3 and 4, iPhone 5 and Samsung Galaxy wifi 5.0 all worked). There doesn't seem to be any way of knowing when these values will be correct, though, so you must monitor them in a script, rather than simply setting the size of your plane/surface/shader at one particular moment.

The solution in brief:

  1. Set the desired resolution to be very high, as rutter suggested.

  2. After asking the camera to start, monitor the size of the texture for a while (keep checking the width and height in the Update method of a script). It should be set to the correct size eventually. (Possibly several frames?)

Note: This solution will only allow you to get the highest available resolution. It would still be better to be able to read a set of supported resolutions ahead of time so you can choose a more appropriate one.

Comment
whydoidoit
PokeJoe
Fattie
Novack
Exceptione

People who like this

5 Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image subjectZero · Mar 04, 2016 at 08:55 AM 2
Share

Hey, Thanks for explaining it, but I'm still a little lost. I've followed all the suggestions but i am still having issues. We have a RawImage 480x480 - here is the code I'm using as suggested by the above answer:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class ShowCameraScript : MonoBehaviour {
 
     public RawImage rawimage;
     private WebCamTexture webcamTexture;
 
     void Start () 
     {
         WebCamDevice[] devices = WebCamTexture.devices;
 
         webcamTexture = new WebCamTexture(devices[0].name,480,480,30);
 
         rawimage.texture = webcamTexture;
         rawimage.material.mainTexture = webcamTexture;
         webcamTexture.Play();
 
     }
 
     void Update()
     {
 
         if ( webcamTexture.width < 100 )
         {
             Debug.Log("Still waiting another frame for correct info...");
             Debug.Log("width is: " + webcamTexture.width.ToString());
 
             return;
         }
 
         // change as user rotates iPhone or Android:
 
         int cwNeeded = webcamTexture.videoRotationAngle;
         // Unity helpfully returns the _clockwise_ twist needed
         // guess nobody at Unity noticed their product works in counterclockwise:
         int ccwNeeded = -cwNeeded;
 
         // IF the image needs to be mirrored, it seems that it
         // ALSO needs to be spun. Strange: but true.
         if ( webcamTexture.videoVerticallyMirrored ) ccwNeeded += 180;
 
         // you'll be using a UI RawImage, so simply spin the RectTransform
         rawimage.rectTransform.localEulerAngles = new Vector3(0f,0f,ccwNeeded);
     
         float videoRatio = (float)webcamTexture.width/(float)webcamTexture.height;
         AspectRatioFitter rawImageARF = rawimage.GetComponent<AspectRatioFitter>();
         rawImageARF.aspectRatio = videoRatio;
 
         if ( webcamTexture.videoVerticallyMirrored )
             rawimage.uvRect = new Rect(1,0,-1,1);  // means flip on vertical axis
         else
             rawimage.uvRect = new Rect(0,0,1,1);  // means no flip
 
         Debug.Log ("videoRatio: "+ videoRatio.ToString());
 
 
     }
 }


Now our aspect ratio should be 1:1 because we are using a 480x480 RawImage but the aspect is ratio is incorrect and is stretched or squashed depending how i hold the device. I've included two images so that you can see what i mean: squashed image - iphone vertical stretched image - iPhone horizontal

is it not possible to make a 1:1 ratio? I've even tried forcing it, but no result. please if anyone can explain or shed some light on the matter it would be appreciated.

We really want to use the 480X480 resolution for our image. so if anyone has a solution for me, that would be awesome. On the other side, if this is a problem, should i submit a bug report?

Thank you in advance for reading this.

img-0031.png (125.1 kB)
img-0032.png (139.1 kB)
avatar image saschandroid subjectZero · Mar 04, 2016 at 01:19 PM 2
Share

I guess the problem is you are getting (for example) 640x480 images from the camera when you're holding the device in horizontal position, and 480x640 in vertical position. You then squeeze these images to fit into 480x480, so once you get horizontal squeezed images (640 to 480 width) and once vertical squeezed images (640 to 480 height).

avatar image Bunny83 saschandroid · Mar 04, 2016 at 02:09 PM 1
Share

Yes, that's most likely the problem. You can't really force a camera chip to a certain aspect ratio since the native aspect ratio is always there. The image would need to be "cropped" in some way so some information of the image would be lost. It certainly doesn't automatically crop the image since there are multiple ways how you could crop an image to a certain resolution.

So you would need to:

  • either crop the image manually by copying only the part you want into your square texture

  • or change UV coordinates of the quad so it only shows the wanted portion

In the following calculations we assume that width is the larger edge and height is the smaller one. If the image is rotated you have to take that into account.

You probably want to crop evenly left and right. So the amount you have to crop on the larger side is:

 float amount = (width - height) * 0.5f;

So "amount" pixels need to be removed from both sides of the larger side.

To calculate the UV coordinates it's quite similar

 float u = (1f - height / width) * 0.5f;

While the "v" coordinates stay at max (one is "0" the other is "1") the u coordinate (along the larger edge of your image) need to be "u" and "1f - u"

avatar image RobertWebb · Oct 15, 2022 at 03:34 AM 0
Share

Has something changed since these answers? I'm testing on an old device, a Galaxy S5 with Android 6.0 (marshmallow), and for me it keeps returning "16x16" forever and camera texture stays black. I'm using Unity 2022.1.11

It works well on my newer Galaxy S9+

On both the S5 and S9+, Permission.HasUserAuthorizedPermission(Permission.Camera) returns true.

Why would WebCamTexture.width and .height keep returning 16x16 every frame?

avatar image

Answer by MorphVGX · Jan 07, 2017 at 01:05 AM

What I found is that the ratio will be correct after the device is set and you call Play() on the WebcamTexture.

Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Unity Answers is in Read-Only mode

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta by June 9. Please note, Unity Answers is now in read-only so we can prepare for the final data migration.

For more information and updates, please read our full announcement thread in the Unity Forum.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Is it possible to render Unity graphics elements on top of iPhone / Android video feed? 2 Answers

Mobile device textfield keyboard keyset - default to numbers 0 Answers

Optimizing OnGUI - Too many gui elements? 2 Answers

Are there some restrictions of filename on Unity(, Android, or iPhone) ? 0 Answers

Editor Play game as device 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges