它可以帮助来形容什么是你的榜样发生的事情:
你把两个矩形的确切大小的屏幕上准确位置(50, 50)
(相对于它们在左上角的起源) 它们都具有默认情况下位于其中心的锚点。想象一下,在这些中心点放一针。 现在你说你实际上想要在右上角的引脚而不是中心。
一两件事情都不会发生,要么
1)的矩形将保持静止,而引脚将自己移动到右上角的角落red:(150, 50)
green:(250, 50)
,这是不是你想要的。
或
2)引脚将保持平稳和矩形将移动本身,直到他们的右上边角其中引脚red pin:(100, 100)
green pin:(150, 200)
,这也不是你想要的!
第二种选择是实际发生的情况。
按照文档的layer.position
相对于layer.anchorPoint
,所以你应该尝试设置anchorPoint
到顶部右上角,然后设置两个矩形层的position
到你想要的确切位置。例如
UIView *v=[[UIView alloc] initWithFrame:CGRectMake(50,50, 100, 100)];
v.backgroundColor=[UIColor redColor];
v.layer.anchorPoint=CGPointMake(1,0);
v.layer.position = CGPointMake(200, 50);
UIView *v2=[[UIView alloc] initWithFrame:CGRectMake(50,50,200,300)];
v2.backgroundColor=[UIColor greenColor];
v2.layer.anchorPoint=CGPointMake(1, 0);
v2.layer.position = CGPointMake(200, 50);
[self.view addSubview:v2];
[self.view addSubview:v];
只是为了好玩:这里是一个动画显示的矩形从最初的位置如何获得initWithFrame
到它们的最终位置,相对于它们的中心锚点。
UIView *v=[[UIView alloc] initWithFrame:CGRectMake(50,50, 100, 100)];
v.backgroundColor=[UIColor redColor];
UIView *v2=[[UIView alloc] initWithFrame:CGRectMake(50,50,200,300)];
v2.backgroundColor=[UIColor greenColor];
[self.view addSubview:v2];
[self.view addSubview:v];
UIView *ap=[[UIView alloc] initWithFrame:CGRectMake(0,0, 10, 10)];
ap.backgroundColor=[UIColor blackColor];
ap.center = v.layer.position;
UIView *ap2=[[UIView alloc] initWithFrame:CGRectMake(0,0, 10, 10)];
ap2.backgroundColor=[UIColor blackColor];
ap2.center = v2.layer.position;
[self.view addSubview:ap];
[self.view addSubview:ap2];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"anchorPoint"];
animation.duration = 2.0;
animation.toValue = [NSValue valueWithCGPoint:CGPointMake(1,0)];
animation.autoreverses = YES;
animation.repeatCount = 10;
[v.layer addAnimation:animation forKey:@"anchorPoint"];
[v2.layer addAnimation:animation forKey:@"anchorPoint"];
是上述代码中'frame'值的正确输出吗?这张照片上的“P(50.f,50.f)”在哪里?如果将'anchorPoint'行注释掉会导致什么结果? – holex 2012-07-18 15:36:10