Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visualizing the Anchor Point of a UIImageView

Is there an easy way of putting a mark (like a cross for example) on the anchor point of an UIImageView? I'm trying to line up several rotating images by their anchor point, and being able to see these points would make the job a lot easier.

Many thanks.

like image 958
Jimmery Avatar asked Jul 16 '13 08:07

Jimmery


1 Answers

You are asking how to visualize the anchor point within a view but it seem to me that you are asking for it so that you can help align the anchor points. I'll try and answer both questions.

Visualizing the anchor point.

Every view on iOS have an underlying layer that has an anchor point. The anchor point is in unit coordinate space of the layer (x and y goes from 0 to 1). This means that you can multiply x by the width and y by the height to get the position of the anchor point inside the layer in the coordinate space of the view/layer. You can then place a subview/sublayer there to show the location of the anchor point.

In code you could do something like this to display a small black dot where the anchor point is.

CALayer *anchorPointLayer = [CALayer layer];
anchorPointLayer.backgroundColor = [UIColor blackColor].CGColor;
anchorPointLayer.bounds = CGRectMake(0, 0, 6, 6);
anchorPointLayer.cornerRadius = 3;

CGPoint anchor = viewWithVisibleAnchorPoint.layer.anchorPoint;
CGSize  size   = viewWithVisibleAnchorPoint.layer.bounds.size;

anchorPointLayer.position = CGPointMake(anchor.x * size.width,
                                        anchor.y * size.height);
[viewWithVisibleAnchorPoint.layer addSublayer:anchorPointLayer];

You can see the result in the image below for four different rotations.

View rotated around anchor point

Aligning layers by their anchor point

That is cool and all but it's actually easier then that to align anchor points.

The key trick is that the position and the anchorPoint is always the same point, only in two different coordinate spaces. The position is specified in the coordinate space of the super layer. The anchor point is specified in the unit coordinate space of the layer.

The nice thing about this is that views that have their position property aligned will automatically have their anchorPoint aligned. Note that the content is drawn relative to the anchor point. Below is an example of a bunch of views that all have the same y component of their position, thus they are aligned in y.

There really isn't any special code to do this. Just make sure that the position properties are aligned.

Multiple views aligned by their anchor point.

like image 174
David Rönnqvist Avatar answered Nov 16 '22 12:11

David Rönnqvist