Dynamically scale images based on parent

Is there a way using unity gui system to dynamically scale images to fit inside the parent image but maintain their ratio. eg if i had a border that was 512521 pixels and 2 images one was 512512 so will fit nicely within the border with no stretching, but then i had a image that was 860*520 so this is bigger than the border and extends over it. What would be the best way to then scale this down in code/ui object so it will fit within the border but maintain its ratio.

Image below kinda shows what the situation is, i just need to dynamically modify the scale of the image so it fits within the box regardless of the image size before hand.

I’m not sure if there exists embedded functionality for this in unity. You will most likely have to do this yourself.

I’m assuming you want to fit one image into another.

Find aspect ratio of both images: imgWidth / imgHeight

if (child_ar > parent_ar)
{
    child_width = parent_width;
    child_height = child_width / child_ar;
}
else
{
    child_height = parent_height;
    child_width = child_height * child_ar;
}