简体   繁体   中英

UIImageView coordinate to subview coordinates

如果我从UIImageView开始并添加了子视图,如何将原始UIImageView中的坐标转换为子视图中的相应坐标(屏幕上相同的位置)?

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).

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;

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM