Tiled background image in custom UIView class

Sometimes you need a repeated or tiled image in your app, often for a background. Something like these rain-drops for example:

Here’s a simple UIView subclass that accepts an image parameter, and renders a repeated tiled image, even in the storyboard:

@IBDesignable
class TiledImageView:UIView {
@IBInspectable var image:UIImage?
override func draw(_ rect: CGRect) {
guard let image = image else {return}
UIColor(patternImage: image).setFill()
let path = UIBezierPath(rect: rect)
path.fill()
}
}

view raw
TiledImageView.swift
hosted with ❤ by GitHub

It creates a patterned image in a UIColor object, sets this as the current fill, and then fills the view’s rect with this color.

Here’s how it looks in the storyboard:

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: ,
Posted in Swift
One comment on “Tiled background image in custom UIView class
  1. […] recently wrote an article on a simple custom UIView class you can use to tile an image. Unfortunately – this […]

Leave a Reply to Tiled a background image – sans code! | Before I forget... Cancel reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: