iOS坐标转换注意

官方提供了4个方法(UIView的方法):

-(CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;//点转换
-(CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;//点转换
-(CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;//矩形转换
-(CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;//矩形转换

屏幕快照 2016-12-08 下午7.40.22.png

获取redView在self.view坐标系中的坐标(以下两种写法等效):

CGPoint redCenterInView = [self.grayView convertPoint:self.redView.center toView:self.view];
 
CGPoint redCenterInView = [self.view convertPoint:self.redView.center fromView:self.grayView];

使用注意:
1.使用convertPoint:toView:时,调用者应为covertPoint的父视图。即调用者应为point的父控件。toView即为需要转换到的视图坐标系,以此视图的左上角为(0,0)点。

2.使用convertPoint:fromView:时正好相反,调用者为需要转换到的视图坐标系。fromView为point所在的父控件。

3.toView可以为nil。此时相当于toView传入self.view.window

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容