Reputation: 9881
I want to implement an image gallery with Unity (2D). I have a Canvas
logically divided into squares of, say, 100x100 units. Then:
I am new to Unity and I already tried a lot of different approaches. My real problem is for the scale and crop. Indeed:
Gui.DrawTexture()
takes an argument scaleMode.ScaleAndCrop
, which is exactly what I need. But this is part of the old UI system...Image
and RawImage
Gui components, but out of the box we can either keep aspect ratio or fill the square, not both.I am sure there is a way to use the new UI functionalities and get the scale and crop effect, but I can't figure out how. Would someone have an advice for me ?
Upvotes: 2
Views: 1506
Reputation: 589
The easiest way to archieve the auto- scale and crop behaviour is to add an an AspectRatioFitter to the GameObject containing the image. Set the AspectMode to Envelope Parent. This way Unity will fill and if needed overlap the parent, see Unity Documentation:
Envelope Parent: The width, height, position, and anchors are automatically adjusted to make the rect cover the entire area of the parent while keeping the aspect ratio. This rect may extend further out than the parent rect.
You can then add a mask to the parent object to hide that unwanted overlay (don't forget to also add an empty image otherwise the mask won't work). The only thing you might have to handle in script is to find the correct aspect ratio of the images.
Upvotes: 0
Reputation: 2720
You will need to use scaling an GameObject with Image component, and using Mask component.
I would do this in this way:
Create canvas with GridLayoutGroup, that will organize the thumbanils Images as you want (3 rows 3 columns etc).
each image has a parent GameObject with mask that will be set with GridLayoutGroup. Child of Mask will be an Image where you will show the downloaded content.
Have a reference to each Image component in controller of your choice.
image1 is a reference to first thumbnail;
When image is downloaded assign made Sprite of it to the image1.sprite.
Call image1.SetNativeSize();
Check the fimage1.GetComponent<RectTransform>().sizeDelta (this is the width and height) and scale the image1 according to the image size, taking in account to fit it into the mask borders. You need basicly some mathematical small algorithm.
The image1 also has Button component with attached OnClick event that will fire the lets say "ShowImagePressed (Image img)". Parameter is the Image of image1.
When this handler is fired, disable the mask by image1.transform.parent.GetComponent<Mask>().enabled = false, and scale the image1, moving it to the center.
Upvotes: 1