Adjusting for Image aspect ratio

You probably noticed that some of your pictures appear squished, especially if they are in a portrait orientation, since our FramedImage is shown at a fixed size and aspect ratio. What we really would like is for the frame and image to adjust themselves depending on the dimensions of the image.

When Unity imports a texture, its pre-processes it by default for GPU rendering as an object material texture, which includes resizing it to a square power of two (for example, 1024 x 1024, 2048 x 2048,and so on). If you adapt your project to read images at runtime, for example, from the Resources directory, the device's photo stream, or over the web, then you will have access to the image file's metadata header that includes its pixel width and height. In lieu of that, since we're using imported textures, we can change the Advanced import settings for the images we're using:

  1. From your Assets Images folder (that is, Assets/Images/) select an image texture.
  2. In Inspector, under Advanced, change Non Power of 2 to None.
  3. Press Apply.

Repeat this for each image in the project. Note that this also decompresses the image, so what might start out as a 400k .jpg file becomes a 3 MB, 24-bit image in the project, so be cautious of the width and height of the source images you choose to use.

In PictureController.cs, add the following helper function, which returns a normalized scale of a texture. The larger dimension will be 1.0 and the smaller one will be a fraction. For example, an image that is 1024w x 768h will get a scale of (1.0, 0.75). It also maintains the current relative scale of the picture using the Z scale value, since that's not changed by our aspect ratio calculation, but will be changed by the Scale tool!

    private Vector3 TextureToScale(Vector3 startScale, Texture texture) { 
        Vector3 scale = Vector3.one * startScale.z; 
        if (texture.width > texture.height) { 
            scale.y *= (texture.height * 1.0f) / texture.width; 
        } else { 
            scale.x *= (texture.width * 1.0f) / texture.height; 
        } 
        return scale; 
    } 
 

Now add a call to it in SetTexture:

    public void SetTexture(Texture texture) { 
        imageRenderer.material.mainTexture = texture; 
        framedImage.transform.localScale = TextureToScale(framedImage.transform.localScale, texture); 
    } 

Press Play, and select an image with a different aspect ratio from the current one. The picture, including its frame, will resize to match its shape. If you use the Scale tool to resize the whole picture, then choose another image; its shape will be adjusted, but the overall scale will be correct.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset