- Home /
How do I properly position dynamically loaded images and maintain aspect ratio ?
I'm working on a 2D project and I'm having a hard time figuring this out.
Currently I load images through an xml file, all of which are located in the StreamingAssets folder. Images are loaded (with a button click) in an image container.
The images can be landscape, portrait or even square, but I need to have the image always be 700px wide, and aligned to the top of the container (a UI Panel).
If I tick "Preserve Aspect", the images are not stretched, which is good, but instead they are fitted into my container, and this results in portrait images having space left and right, and landscape images having space above and below the image.
I have also tried the Rect Transform align tools, the layout components, the aspect ratio fitter and also the Rect Mask 2D.
Whatever I try, I simply cannot get my image aligned to the top and filled horizontally (700px wide the width of the image container).
If I need to tackle this in code, that's fine, but I have no idea where to start.
Any help is appreciated (...as I've been trying to get this right all day and haven't come up with a solution).
Answer by FernandoHC · Aug 15, 2018 at 05:34 PM
You want to use the texture width and height and compare with the container size, so you can shift the position relatively.
I have written an example code for you that can do that, it only changes Y for now, but you can change it to whatever you want:
public Image image;
public RectTransform rectTransform;
public float scaleConstant = 1f;
public void AdjustImage()
{
float topDistance = rectTransform.rect.height - image.sprite.texture.height;
Vector3 position = transform.localPosition;
position.y = topDistance * scaleConstant;
transform.localPosition = position;
}
Fernando, thanks so much for this. This helped tremendously and I wouldn't have found this solution by myself.
I am now succesfully moving the images along the y axis !
Your answer
![](https://koobas.hobune.stream/wayback/20220612172853im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Custom Editor: InspectorGUI showing sprite variables,Lists,transform variables,... 0 Answers
Sprite moving too far/fast 1 Answer
How to dynamically set transform positions (for a Bezier curve)? 2 Answers
how to make a sprite face your character on one axis? 0 Answers
How to draw a Sprite next to theplayer 0 Answers