iOS转换坐标

2018-03-20  本文已影响11人  AprSnow

方法

ios转换坐标有两个方法:convertRect:fromView:convertRect:toView:,本文介绍这两个方法的用法。

首先考虑如下代码:

UIView *viewA = [[UIView alloc] initWithFrame:
                            CGRectMake(0, 100, self.view.frame.size.width, 400)];
UIView *viewB = [[UIView alloc] initWithFrame:
                            CGRectMake(0, 50, 150, 150)];

[viewA addSubview:viewB];
[self.view addSubview:viewA];

CGRect rect1 = [self.view convertRect:viewB.frame fromView:viewA];
CGRect rect2 = [self.view convertRect:viewB.frame toView:viewA];

rect1rect2 分别是什么位置?

ViewA and ViewB

convertRect:fromView:

Converts a rectangle from the coordinate system of another view to that of the receiver.

把一个矩形从另一个视图的坐标系转换到接受者的坐标系。

CGRect rect1 = [self.view convertRect:viewB.frame fromView:viewA];
// rect = (origin = (x = 0, y = 150), size = (width = 150, height = 150))

从代码中可以看出,rect1 表示 viewA 中的 viewBself.view 坐标系中的位置。

convertRect:toView:

Converts a rectangle from the receiver’s coordinate system to that of another view.

把一个矩形从接受者的坐标系转到另一个视图的坐标系。

CGRect rect2 = [self.view convertRect:viewB.frame toView:viewA];
// rect = (origin = (x = 0, y = -50), size = (width = 150, height = 150))

从代码中可以看出,rect2 表示在self.view坐标系中,viewB( frame = (0, 50, 150, 150) )相对于viewA( frame = (0, 100, width, 400) )的位置。

上一篇下一篇

猜你喜欢

热点阅读