Forum Archive

Set background image of view

Webmaster4o

Can a ui.view have a background image? If so, how do I do this?

Also, if not, what is the best way to make an ImageView that scales to fit the view without changing the aspect ratio of the image?

omz

You can set the content_mode attribute of an ImageView to either ui.CONTENT_SCALE_ASPECT_FIT or ui.CONTENT_SCALE_ASPECT_FILL, depending on the look you're trying to achieve.

Here's a visual explanation of the difference between those two modes:

→ UIImageView Scaling Explained Visually

Webmaster4o

Thanks, @omz

ccc

You can also layer one view on top of another and set the .alpha value of the front view to allow the image on the back view to bleed thru. An editable text view as foreground with an image view as background.

import ui
image_view = ui.ImageView()
image_view.image = ui.Image.named('Snake')
image_view.present()
text_view = ui.TextView(frame=image_view.bounds)
text_view.text = '1234567890 ' * 700
text_view.alpha = 0.5
image_view.add_subview(text_view)
dgelessus

An editable text view as foreground with an image view as background.

Now that you mention it, this sounds like the perfect way to implement a multi-color text field. The text field itself has a transparent background and text and is only used to provide standard text view functionality (selection, copy-paste, etc.). The text is actually displayed by a custom view below, which updates whenever the text field's text changes.