Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoresize sublayers

I have an imageview and on button click I draw some bezier paths and some text layer too. On undo, I've removed last drawn path and text layer.

Now I want to resize my image View to set up in uper half portion of view and duplicated in lower half view, and want to resize all layers at the same time and also want to continue drawing after that.

like image 390
Eager Beaver Avatar asked Jan 30 '13 13:01

Eager Beaver


2 Answers

Its too late to answer...

But may be this can help others. There is no autoresize masks for CALayers You can manage that with some tricks..

- (void)layoutSubviews {
  // resize your layers based on the view's new frame
  layer.frame = self.bounds;
}

This will work if you have created a subclass of UIView. If not that, you can just set the bounds to the frame of CALayer anywhere if you have reference to your layer.

like image 70
DivineDesert Avatar answered Oct 20 '22 14:10

DivineDesert


At least there are 3 options:

  1. use delegate of CALayer
  2. override layoutSublayers, and call it by setNeedsLayout()
  3. use extension and call view's fitLayers

Example below, option 3:

Swift 5, 4

Code

extension UIView {
  func fitLayers() {
    layer.fit(rect: bounds)
  }
}

extension CALayer {
  func fit(rect: CGRect) {
    frame = rect

    sublayers?.forEach { $0.fit(rect: rect) }
  }
}

Example

// inside UIViewController 
override func viewWillLayoutSubviews() {    
  super.viewWillLayoutSubviews()

  view.fitLayers()
}

// or
// inside UIView
override func layoutSubviews() {    
  super.layoutSubviews()

  fitLayers()
}
like image 21
dimpiax Avatar answered Oct 20 '22 14:10

dimpiax