Alex B
Alex B

Reputation: 84942

Apply rotate transform to tiled background image

Is there a simple way to render a rotated tiled image as a view background? Something to the effect of UIColor(patternImage:) but where the image is rotated at a certain angle?

Upvotes: 0

Views: 334

Answers (2)

Alex B
Alex B

Reputation: 84942

Turns out Core Image filter CIAffineTile does exactly what I want.

extension UIImage {
    func tile(angle: CGFloat) -> CIImage? {
        return CIImage(image: self)?.applyingFilter(
            "CIAffineTile",
            withInputParameters: [
                kCIInputTransformKey: NSValue(
                    cgAffineTransform: CGAffineTransform(rotationAngle: angle)
                )
            ]
        )
    }
}

This function creates a CIImage with infinite extent, which can be cropped and converted to a real image.

let v = UIImageView()

// ...

let source = UIImage(named: "sample")!
let tiled = source.tile(angle: CGFloat.pi / 6)!
let result = UIImage(ciImage: tiled.cropping(to: v.bounds))

v.image = result

Upvotes: 1

glyvox
glyvox

Reputation: 58139

There is no simple way to achieve this, at least not in vanilla Swift. I would use another UIView as a subview for our original view, set its background to a tiled image and add a CGAffineTransform to that particular view.

Upvotes: 1

Related Questions