Tiled Background Image: Can I do that easily with UIImageView?

前端 未结 7 1085
甜味超标
甜味超标 2020-12-07 13:05

I have a fullscreen background image that is tiled, i.e. it has to be reproduced a few times horizontally and vertically in order to make a big one. Like in the browsers on

7条回答
  •  一生所求
    2020-12-07 13:42

    In WWDC 2018 video session 219 - Image and Graphics Best Practices, Apple engineer explicitly recommends not to use the pattern color for tiling backgrounds:

    I recommend not using patterned colors with a background color property on UIView. Instead, create a UIImageView. Assign your image to that image view. And use the functions on UIImageView to set your tiling parameters appropriately.

    So the best and simplest way to create a tiled background would be like this:

    imageView.image = image.resizableImage(withCapInsets: .zero, resizingMode: .tile)
    

    Or even simpler, if you use asset catalog – select your pattern image asset and, in the Attributes inspector, enable Slicing (Horizontal/Vertical or both), set the insets to zero, and width/height to the dimensions of your image:

    then simply assign this image to your image view (Interface Builder works, too), just don't forget to set the UIImageView's contentMode to .scaleToFill.

提交回复
热议问题