iPadDeveloper2011
iPadDeveloper2011

Reputation: 4685

UIImageView coordinate to subview coordinates

If I start with a UIImageView, and I add a subview, how do I translate a coordinate in the original UIImageView to a corresponding coordinate (the same place on the screen) in the subview?

Upvotes: 2

Views: 2341

Answers (3)

Lily Ballard
Lily Ballard

Reputation: 185831

UIView provides methods for exactly this purpose. In your case you have two options:

CGPoint newLocation = [imageView convertPoint:thePoint toView:subview];

or

CGPoint newLocation = [subview convertPoint:thePoint fromView:imageView];

They both do the same thing, so pick whichever one feels more appropriate. There's also equivalent functions for converting rects. These functions will convert between any two views on the same window. If the destination view is nil, it converts to/from the window base coordinates. These functions can handle views that aren't direct descendants of each other, and it can also handle views with transforms (though the rect methods may not produce accurate results in the case of a transform that contains any rotation or skewing).

Upvotes: 6

iPadDeveloper2011
iPadDeveloper2011

Reputation: 4685

Starting with code like:

UIImageView* superView=....;
UIImageView subView=[
    [UIImageView alloc]initWithFrame:CGRectMake(0,0,subViewWidth,subViewHeight)
];
subView.center=CGPointMake(subViewCenterX, subViewCenterY);
[superView addSubview:subView];

The (subViewCenterX, subViewCenterY) coordinate is a point, in superView, where the center of subView is "pinned". The subView can be moved around wrt the superView by moving its center around. We can go, for example

subView.center=CGPointMake(subViewCenterX+1, subViewCenterY);

to move it 1 point to the right. Now lets say we have a point (X,Y) in the superView, and we want to find the corresponding point (x,y) in the subView, so that (X,Y) and (x,y) refer to the same point on the screen. The formula for x is:

x=X+subViewWidth/2-subViewCenterX;

and similarly for y:

y=Y+subViewHeight/2-subViewCenterY;

To explain this, if you draw a box representing the superView, and another (larger) box representing the subView, the difference subViewWidth/2-subViewCenterX is "the width of the bit of the subView box sticking out to the left of the superView"

Upvotes: 0

jamihash
jamihash

Reputation: 1900

Subtract the subview's frame.origin from the point in the parents view to the same point in the subview's coordinate:

subviewX = parentX - subview.frame.origin.x;

subviewY = parentY - subview.frame.origin.y;

Upvotes: 0

Related Questions