将CGPoint从UIView坐标系转换为CALayer坐标系

Cor*_*oyd 11 iphone cocoa-touch core-animation

有一些方法可以将CGPoint从一个UIView转移到另一个UIView,从一个CALayer转移到另一个.我找不到将CGPoint从UIView的坐标系更改为CALayer坐标系的方法.

图层及其主视图是否具有相同的坐标系?我需要在它们之间转换点吗?

谢谢,科里

[编辑]

谢谢你的回答!很难找到有关iPhone和Mac上CA之间差异/相似性的信息.我很惊讶我发现在任何Apple文档中都没有直接解决这个问题.

我正在寻求这个答案,以帮助解决我正在排除故障的错误,这是我最好的猜测,但我想我正在咆哮错误的树.如果坐标系是相同的,那么我有另一个问题......

我可以在Stack Overflow上找到我遇到的实际问题: 图层命中测试仅在触摸图层的下半部分时返回图层

sch*_*hwa 13

hitTest的文档说:

/* Returns the farthest descendant of the layer containing point 'p'.
 * Siblings are searched in top-to-bottom order. 'p' is in the
 * coordinate system of the receiver's superlayer. */
Run Code Online (Sandbox Code Playgroud)

所以你需要做(像这样):

CGPoint thePoint = [touch locationInView:self];
thePoint = [self.layer convertPoint:thePoint toLayer:self.layer.superlayer];
CALayer *theLayer = [self.layer hitTest:thePoint];
Run Code Online (Sandbox Code Playgroud)


ott*_*tto 5

在Apple文档方面,我在《核心动画编程指南》(2008-11-13)的“层坐标系统”部分中找到了“ iPhone OS Note” 。

UIView实例的默认根层使用与UIView实例的默认坐标系匹配的翻转坐标系-原点位于左上角,而值则向右下方递增。通过实例化CALayer创建的图层直接使用标准的Core Animation坐标系。


Lil*_*ard 4

transform如果你想翻转它们的坐标系,你可以将 CALayers 的属性设置为适当的变换,但请注意,这也可能会翻转它们的绘图contents(我没有测试过,但这是有道理的) 。我关于与 UIView 关联的 CALayer 共享相同坐标系的断言实际上可能是完全错误的。也可能 CALayers 使用与 UIView 相同的坐标系(即它们从不垂直翻转),但我认为它们是因为 CoreGraphics 使用相对于 UIKit 的翻转坐标系。

一个简单的测试方法是添加一个屏幕大小的 CALayer 作为视图层的子层,然后添加另一个小的 CALayer 作为其子层。您可以将其设置为显示在 (0, 0, 320, 100),然后查看它是否显示在 iPhone 屏幕的顶部或底部。这将告诉您 CoreAnimation 的 Y 轴走向哪个方向。

- (void)viewDidLoad {
  [super viewDidLoad];
  CALayer *rootLayer = [CALayer layer];
  rootLayer.frame = self.view.layer.bounds;
  CALayer *smallLayer = [CALayer layer];
  smallLayer.frame = CGRectMake(0, 0, rootLayer.bounds.size.width, 50);
  smallLayer.backgroundColor = [UIColor blueColor].CGColor;
  [rootLayer addSublayer:smallLayer];
  [self.view.layer addSublayer:rootLayer];
}
Run Code Online (Sandbox Code Playgroud)

我自己刚刚进行了这个测试,看来 CALayers 实际上使用了与 UIView 相同的坐标系,所以我关于 CALayer 翻转 Y 轴的断言肯定是错误的。但是,如果您直接使用 CoreGraphics 进行绘图,请注意 CoreGraphics确实使用翻转的 Y 轴(尽管在 UIView 子类或我假设是 CALayer 委托中绘图时,CoreGraphics 上下文已被翻转以匹配 UIView 的(或CALayer 的坐标系)。

因此,如果您到目前为止已经做到了,那么简短的答案是 CALayer 的坐标系应该与其相应的 UIView 的坐标系相匹配。