user4806509
user4806509

Reputation: 3011

How to tile an image from center using UIColor patternImage in Swift

I have a method for repeating or tiling an image across a view using UIColor patternImage:

view.backgroundColor = UIColor(patternImage: UIImage(named:imageName))

The default behaviour of UIColor patternImage is to start the pattern from the top left, the result shown in Image 1.

Question:

How can I get UIColor patternImage to start always from the very center of a view, patterning outwards to give the result shown in Image 2?

enter image description here

enter image description here

Upvotes: 3

Views: 3908

Answers (3)

Nikita Ivaniushchenko
Nikita Ivaniushchenko

Reputation: 1435

I created reusable class PatternView, reusing idea of @user4806509. It's really drop-in component for showing patterns. Also, patternImage can be set via Interface Builder

class PatternView: UIView {
   @IBInspectable var patternImage: UIImage?

    override func awakeFromNib() {
       super.awakeFromNib()

       self.setupBackgroundColor()
   }

    private func setupBackgroundColor() {
       guard let patternImage = self.patternImage else {
          return
       }

       self.backgroundColor = UIColor(patternImage: patternImage)
   }

   override func layoutSubviews() {
      super.layoutSubviews()

      self.centerPattern()
   }

   private func centerPattern() {
       guard let patternSize = self.patternImage?.size,
             patternSize.width > 0, patternSize.height > 0 else {
          return
       }

      let x = -self.bounds.width.remainder(dividingBy: patternSize.width)/2
      let y = -self.bounds.height.remainder(dividingBy: patternSize.height)/2
      self.bounds.origin = CGPoint(x: x, y: y)
  }}

Upvotes: 0

user4806509
user4806509

Reputation: 3011

This works. It is a generalised method that applies more broadly, adapting dynamically to both pattern images and views of different heights and widths. It gives the desired result in the question and is tested on different iOS simulators.

view.backgroundColor = UIColor(patternImage: UIImage(named: "imageName")!)
view.bounds.origin.x = (UIImage(named: "imageName")!.size.width/2) - (view.bounds.size.width/2)
view.bounds.origin.y = (UIImage(named: "imageName")!.size.height/2) - (view.bounds.size.height/2)

Upvotes: 6

Ketan Parmar
Ketan Parmar

Reputation: 27438

If your image size is 50*50 then you can do something like this,

 myView = UIVIew(frame: CGRect(x: (self.view.frame.size.width/2)-25, y: (self.view.frame.size.height/2)-25, width: 50, height: 50))

So this view(imageview in yourcase may be) will be place at exact middle of view. Like wise you can arrange other view by adding or substracting view's width and height to center view's x and y origin. Hope this will help you. :)

Upvotes: 0

Related Questions