有一些方法可以将CGPoint从一个UIView转移到另一个UIView,从一个CALayer转移到另一个。我找不到将CGPoint从UIView的坐标系更改为CALayer坐标系的方法。
图层及其主视图是否具有相同的坐标系?我需要在它们之间转换点吗?
谢谢, 科里
[编辑]
谢谢你的回答!很难找到有关iPhone和Mac上CA之间差异/相似性的信息。我很惊讶我发现在任何Apple文档中都没有直接解决这个问题。
我正在寻求这个答案,以帮助解决我正在排除故障的错误,这是我最好的猜测,但我想我正在咆哮错误的树。如果坐标系是相同的,那么我有另一个问题......
我可以在Stack Overflow上找到我遇到的实际问题: layer hit test only returning layer when bottom half of layer is touched
答案 0 :(得分: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. */
所以你需要做(像这样):
CGPoint thePoint = [touch locationInView:self];
thePoint = [self.layer convertPoint:thePoint toLayer:self.layer.superlayer];
CALayer *theLayer = [self.layer hitTest:thePoint];
答案 1 :(得分:4)
如果要翻转坐标系,可以将CALayers的transform
属性设置为适当的变换,但请注意,这可能会翻转contents
的绘图(我没有测试了,但这是真的有意义)。我断言与UIView相关联的CALayer共享相同的坐标系统实际上可能完全是错误的。它也可能是CALayers使用与UIViews相同的坐标系统(即它们从不垂直翻转),但我认为它们是因为CoreGraphics使用相对于UIKit的翻转坐标系。
一种简单的测试方法是添加一个屏幕大小的CALayer作为视图图层的子图层,然后添加另一个小CALayer作为其子图层。您可以将其设置为显示在(0,0,320,100)并查看它是否显示在iPhone屏幕的顶部或底部。这将告诉您Y轴进入CoreAnimation的方向。
- (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];
}
我自己刚刚进行了这个测试,看起来CALayers实际上使用的是与UIViews相同的坐标系,所以我断言CALayer翻转Y轴肯定是错误的。但是,如果直接使用CoreGraphics进行绘制,请注意CoreGraphics 使用翻转的Y轴(尽管在UIView子类中绘制或者假设是CALayer委托时,CoreGraphics上下文已经被翻转以匹配UIView(或CALayer)的坐标系。)
所以简短的回答,如果你做到这一点,那么CALayer的坐标系应该与其相应的UIView的坐标系匹配。
答案 2 :(得分:4)
就Apple文档而言,我在Core Animation Programming Guide(2008-11-13)的层次坐标系部分找到了“iPhone OS Note”。
UIView实例的默认根层使用与UIView实例的默认坐标系匹配的翻转坐标系 - 原点位于左上角,值向下和向右增加。通过实例化CALayer创建的图层直接使用标准的Core Animation坐标系。
答案 3 :(得分:1)
从我的测试中我发现子图层与它的父图层共享相同的坐标系,因此如果要将子图层添加到UIView图层,那么它们将共享相同的坐标系。
如果您仍想要翻转坐标系,使其原点位于左上角,则应使用此转换来翻转y轴。 (x,y,1)=(x',y',1)* [1 0 0],[0 -1 0],[0 heigth 1]
翻译成代码的是: [your_layer setAffineTransform:CGAffineTransformMake(1,0,0,-1,0,heigth)];
答案 4 :(得分:0)
我相信UIView及其关联层的坐标系应该是相同的。但是,如果您自己创建图层,则垂直翻转坐标系。
答案 5 :(得分:0)
Methods that fixing frames and points
- (CGRect) fixRect:(CGRect)rect inRect:(CGRect)container
{
CGRect frame = rect;
frame.origin.y = container.size.height - frame.origin.y - frame.size.height;
return frame;
}
- (CGPoint) fixPoint:(CGPoint)point fromPoint:(CGSize)containerSize
{
CGPoint frame = point;
frame.y = size.height - frame.y;
return frame;
}
答案 6 :(得分:-2)
我相信两者有相同的坐标系。