Creating patterns with UIColor. Yes, really

Short post about fun usage of UIImage inside of UIColor.

Published: Jan. 30, 2022
See books

I think as an iOS developer you are probably deeply familiar with UIColor. But have you ever noticed this initializer?

UIColor(patternImage:)

This will let you create a "color" out of an image. You can use any UIImage you want. If the size of element you apply this "color" to is larger than the image, the image will get repeated until it covers the whole space.

With this initializer you can spice up your apps with patterns. If you don't mind the lack of control.

The only way to control how UIColor created out of UIImage looks like, is to manipulate the UIImage directly. So if you need the pattern to be of certain color, you need to set the color on the image.

In my testing using SF Symbols as "patterns" worked pretty well, but I was unable to change the color from black. Using the withTintColor method on UIImage had no effect.

Although I was able to modify the symbol size using the UIImage.Configuration options:

let config = UIImage.SymbolConfiguration(font: .systemFont(ofSize: 40))
let pattern = UIColor(patternImage: UIImage(systemName: "heart", withConfiguration: config)!)
patternView.backgroundColor = pattern

And the result is something like this:

Pattern with UIColor and UIImage

See how the symbols are cut when the view ends? This is another limitation you cannot easily overcome. Some patterns look better than others with these cut offs.

While this UIColor "option" is something I ever only used once in a "real project" I nevertheless wanted to share it because it is an interesting option we have.

For more customizable patterns I would encourage you to look into Core Graphics to draw them manually - either from basic shapes or repeating UIImage on the canvas.

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀

iOS blogger and developer with interest in Python/Django. Want to see most recent projects? 👀