- Home /
Scale UI Image source image
Hi Unity Community
I have a UI Image whose Source Image is assigned at runtime. These images will be of various sizes and I need them to be scaled to fit the bounds of the layout element so that the entire image is visible.
I have tried a number of approaches for this, however I can’t seem to get this to work; could anyone please provide me some pointers on how to achieve this?
Many thanks in advance, Ryan
Current Code:
public function ContextImgImp(){
Debug.Log("Context Img Located at: " + texLocation);
var wwwDirectory = "file://" + texLocation; //this will probably need to change for other OS (PC = file:/ [I think?]) - **REVISE**
Debug.Log("Tex located at: " + wwwDirectory);
newImgTex = new Texture2D(512, 512, TextureFormat.DXT1, false);
while(true){
var www : WWW = new WWW(wwwDirectory);
yield www;
Debug.Log("Done Downloading Texture");
www.LoadImageIntoTexture(newImgTex);
if (www.isDone){
break; //if done downloading image break loop
}
}
var imgSprite = contImg.sprite;
var imgRect = imgSprite.rect;
var imgPivot = imgRectTrans.pivot;
var pixelScale = 100;
Debug.Log("Pixel Scale:" + pixelScale);
newImgSprite = Sprite.Create(newImgTex, imgRect, imgPivot, pixelScale);
contImg.sprite = newImgSprite;
//imgRectTrans.rect.size = Vector2(130,130);
//contImg.sprite.rect.size = Vector2(130,130);
//contImg.type = Image.Type.Simple;
}
Current image display:
Whole image to be displayed:
Forgot to mention that the layout is controlled via Layout Groups, which conflicts for control over the rect with other potentially useful Layout Compoonents such as Aspect Ratio Fitter and Content Size Fitter etc
One potential approach to resolving this I considered was creating a smaller thumbnail image in the import. I did a bunch of trials with various source image sizes and this certainly changed the way the image is being cropped. However trails at the rect size (130px) were not possible due to the $$anonymous$$imum size for the source img being 132px. The 132px size (included in image) still incurred cropping.
Can anyone provide me any pointers as to how this issue can be resolved? Getting no responses on this.
Answer by itsharshdeep · Sep 17, 2015 at 06:23 AM
Can Layout element allowing you to make the anchor like same as I posted the screenshot, If yes then pls check with the same. May be it work
Hi itsharshdeep, thanks for your response
I tried this out, doesn’t affect anything. I’m pretty sure this is overridden by the parent layout group components.
Expanding the rect size to account for the size of the image isn’t really what I’m after; I’m ai$$anonymous$$g to scale the image to fit the rect size, not vice versa.
Ok :)
Sorry I dont have any idea about this. Lets hope that Some more knowledgeable person will come and respond on this
Your answer
