2

I want to implement scrollview in Unity3D 5 UI with horizontal images downloaded from web, they have different random aspect ratios, but I want them to be constant height. And width to be according their aspect ratio, like this:

enter image description here

I tried to use Horizontal Layout Group, but images get too little, so it can all fit in group, when I want them to be constant height and stretch parent's width. So, like, parent's widht is primary and it affects children, but I want children to affect total parent's width (expand it when adding new children images).

Any ideas how to achieve this? Thanks.

Roman
  • 1,946
  • 3
  • 20
  • 28

1 Answers1

4

You need to use ScrollView with horizontal scrolling enabled and vertical scrolling disabled. Setup your hierarchy as in the image below:

enter image description here

On the GameObject named Content attach Horizontal Layout Group and Content Size Fitter with the following settings:

enter image description here

Then on all your images attach a Layout Element component and during runtime calculate the width using the aspect ratio of the image and height to the Content gameobject and assign this width to Preferred Width property of Layout Element Component: In the following image 300 is the calculated width for the image:

enter image description here

As a result any images you add as child to the Content gameobject will increase their parent's width and also you will be able to scroll horizontally to view all the image.

p.s. I wrote this answer in a hurry. Hopefully it will make sense to you if not let me know and I will improve my answer.

Anas iqbal
  • 1,036
  • 8
  • 23