Search Unity

Unity UI Display loaded UI Image in Container with native size

Discussion in 'Unity UI & TextMesh Pro' started by siddharth3322, Jun 13, 2018.

  1. siddharth3322


    Nov 29, 2013
    I want to display UI logo images in their aspect ratio but in proper size that fit within its container. Already all logo images as per aspect ratio but few are too big or small compare to requirements.

    At present this kind of thing happening:

    Here is the code that I am using:

    Code (CSharp):
    1. private void ShowGamePlayLogoViewed ()
    2. {
    3.     for (int i = 0; i < DataCollection.companyDetailsList.Count; i++) {
    4.         Company company = DataCollection.companyDetailsList [i];
    5.         if (company.ViewedCounter > 0) {
    6.             GameObject companyItemObj = Instantiate (companyItemPref, gridViewContainer) as GameObject;
    7.             CompanyItem companyItem = companyItemObj.GetComponent<CompanyItem> ();
    8.             companyItem.companyId = company.CompanyId;
    9.             companyItem.UpdateCompanyLogo (company.CompanyLogo);
    10.             companyItem.UpdateCompanyName (company.CompanyName);
    11.         }
    12.     }
    13. }
    14. public void UpdateCompanyLogo (Sprite logoSprite)
    15. {
    16.     logoImage.sprite = logoSprite;
    17.     logoImage.SetNativeSize ();
    18. }
    As per you are seeing, logos overlapping the container. I want to display properly them in their respective containers also in aspect ratio too.

    Please give me some help so that I can set properties like that way. Let me clear one more thing, all logos loaded from web server and they all are dynamic at a time, based on server data it will appear in mobile screen.
    Last edited: Jun 13, 2018
  2. Hosnkobf


    Aug 23, 2016
    adjust the image game object inside unity so that it has the height you are looking for. also adjust the anchors so that it scales with different resolutions properly.
    Add an "AspectRatioFitter" component to the object. Make it "Height controls width".
    Instead of
    logoImage.SetNativeSize ();
    do the following:
    Code (CSharp):
    1. float aspectRatio = logoSprite.rect.width / logoSprite.rect.height;
    2. var fitter = logoImage.GetComponent<UnityEngine.UI.AspectRatioFitter>();
    3. fitter.aspectRatio = aspectRatio;
    siddharth3322 likes this.
  3. siddharth3322


    Nov 29, 2013
    @Hosnkobf thank you so much for your clever help :)
    This work perfectly for my requirements.
    Hosnkobf likes this.