Caroline
Caroline

Reputation: 4970

How to Size UIView from its CALayers?

I have a UIView with a hierarchy of CALayers.

I am creating the layers using images, so I don't know the final size of the UIView until I have completed creating the layers.

How would I find out a final UIView size that allows touches to all the layers?

It's also complicated by the fact that a layer might be rectangular, and then rotated, so that it sticks out further. I wouldn't be able to use the frame size of the layer, because of its affine transform.

I do have a solution that makes one UIView the size of the screen, and I can add all my CALayers to this UIView, but I will have several sets of these layer hierarchies, which I would prefer to be in separate UIViews so that I can use UIView gestures to translate/scale/rotate.

Upvotes: 0

Views: 140

Answers (1)

debleek63
debleek63

Reputation: 1189

You can use CGMutablePathRef for this. And then loop over all CALayer-s in view.layer.sublayers:

CGPathAddRect(path,
              &transform,
              CGRectOffset(i.bounds,
                           -CGRectGetMidX(i.bounds), 
                           -CGRectGetMidY(i.bounds)));

Rectangle is offset to have its center in CGPointZero. The transform here is rotation of your layer (or scale) plus translation to layer's position. I.e.:

CGAffineTransform transform =
    CGAffineTransformConcat(CATransform3DGetAffineTransform(i.transform),
                            CGAffineTransformMakeTranslation(i.position.x,
                                                             i.position.y));

Finally:

view.bounds = CGPathGetBoundingBox(path);

Bounds now are minimal and enclose all layers.

Upvotes: 1

Related Questions