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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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() | |
} | |
} |
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:
[…] recently wrote an article on a simple custom UIView class you can use to tile an image. Unfortunately – this […]