How to autoresize sublayers
Asked Answered
W

2

7

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.

Walli answered 30/1, 2013 at 13:33 Comment(2)
Duplicate your view i.e other instance of its class with same attributes.apply cgaffinetranslation 1/2 on xscale. on both copies place one below other see if it worksGimmal
I think you are not updating your bezier path while resizing the image view. You can find a way for updating bezier path here #13524522Residue
U
21

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.

Uncertainty answered 14/5, 2013 at 12:41 Comment(2)
Thanks +1! it's work for me with: self.sublayer.frame = self.layer.bounds;Lasandralasater
But it doesn't work with autolayouted view with CALayers while rotate :))Iphigenia
U
4

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()
}
Unseemly answered 15/8, 2018 at 17:45 Comment(1)
Thank you! If you're going to use it in the UIView, you need to subclass UIView: import UIKit class CustomView : UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func layoutSubviews() { super.layoutSubviews() fitLayers() } }Hopping

© 2022 - 2024 — McMap. All rights reserved.