- Home /
How do I anchor sprite positions to an Image with "Preserve Aspect" set?
You can see in the image I have a background image with some trees, and it is set to Preserve Aspect. So even though the screen has been set to a resolution with the wrong aspect ratio for the image, it's still displaying properly.
The panel it's on is larger than the image because of this. My problem is that I want the objects in the scene (the bugs) to maintain their location relative to the image, not the panel.
The anchors care about the panel's size, not the image's size. Is there a way for me to get this to work?
I've tried using an AspectRatioFitter as suggested by one of the answers, and I get this. The blue dots show the size of the fitter is correct, but its anchors are in the same place as the parent RectTransform, which means it doesn't change the location behavior of the objects.
http://i23.photobucket.com/albums/b362/almo2001/Work/Untitled9_zpsdf7f2c1c.jpg
Answer by troien · Nov 24, 2014 at 11:03 PM
Give the image a AspectRatioFitter and set it to the aspect ratio of the image (The mode should be FitInParent). This way the actual RectTransform it's height/width are set to this aspect ratio.
Ok, I have a panel with an image in it, and a gameobject with the Fitter as child of that panel. I set the AspectRatioFitter to FitInParent, and it seems to be setting its anchors according to the size of the RectTransform, not the image itself. So the image maintains aspect, but the AspectRatioFitter is putting its anchors in exactly the same place as the parent, which make its RectTransform larger than the image. :(
This appears to be a bug in the AspectRatioFitter. It is supposed to maintain aspect ratio for its anchors, but it does not. I have reported it to Unity.
If you set it to fit in parent, you can also give it a float value. Try to give it a value which is your image's width / height (in pixels)
Yup, did that. Set it to 1.3333, which makes the blue dots go to the right place, but not the white arrows.
I believe that is expected behaviour, as the AspectRatioFitter sets the RectTransforms width/height, so that the rect maintains the aspect ratio.
In case of FitInParent or Envelope Parent, it sets it's anchors to $$anonymous$$ 0,0 and max 1,1. (Because that is the size of the parent), and then changes w-dalta/h-delta values to make sure the aspect ratio is maintained.
Child components also look at the parent's rect (the area between the 4 blue dots). Not the parent's anchors! The anchors are only used to calculate the rect.
Your answer
Follow this Question
Related Questions
Sprite in different aspect ratio 0 Answers
Unity 2D targeting multiple screen sizes 1 Answer
Changing sprite at runtime causes it to stop resizing 1 Answer
Inconsistent Sprite location on screen 1 Answer
Handling Multiple Resolutions in 2D? 0 Answers