I am trying to create a background image that covers the entire screen of my phone, while at the same time keeps its original aspect ratio. This means that if the image and screen do not have the same aspect ratio, parts of the image will be cropped. This is acceptable. Needless to say that I want it to work with any image or screen size. I wrote a code that uses a SpriteRenderer and it appears to work as described above. It compares the two aspect ratios, and then adjust the pixelsPerUnit accordingly. If the image aspect ratio is smaller than the screen aspect ratio, it ensures that the width of the image matches the width of the screen. Otherwise, it matches the height of the screen. I should also point that I am using an orthographic camera.
backgroundRootGO = new GameObject("Root");
backgroundImageGO = new GameObject("Image");
backgroundImageGO.transform.parent = backgroundRootGO.transform;
spriteRenderer = backgroundImageGO.AddComponent<SpriteRenderer>();
backgroundRootGO.transform.parent = GameContext.RootGameObject.transform;
var cam = Camera.main;
var screenSizeY = 2f * cam.orthographicSize;
var screenSizeX = screenSizeY * cam.aspect;
var textureSizeX = (float)texture.width;
var textureSizeY = (float)texture.height;
var pixelsPerUnit = 0.0f;
var screenAspect = screenSizeX / screenSizeY;
var textureAspect = textureSizeX / textureSizeY;
if (textureAspect < screenAspect) {
pixelsPerUnit = textureSizeX / screenSizeX;
} else {
pixelsPerUnit = textureSizeY / screenSizeY;
}
var spriteRect = new Rect(0, 0, texture.width, texture.height);
var spritePivot = new Vector2(0.5f, 0.5f);
var imageSprite = Sprite.Create(texture, spriteRect, spritePivot, pixelsPerUnit);
spriteRenderer.sprite = imageSprite;
However, I would like to produce the same result using a Canvas. Unfortunately, I am not quite sure how to do so. I find Canvas and CanvasScaler hard to use. I understand the basic concepts like Render Mode, UI Scale Mode, etc. But things like Screen Match Mode, Match, Reference Resolution, and Anchors confuse me.
Any advice, pointers, and code snippets would be highly appreciated. Thank you!
PS: I am using Unity 2022.3.