两个UIView具有相同的锚点
我一直在尝试下面的代码,以交叉两个UIView与anchorPoint(1,0)。两个UIView具有相同的锚点
UIView *v=[[UIView alloc] initWithFrame:CGRectMake(50,50, 100, 100)];
v.backgroundColor=[UIColor redColor];
v.layer.anchorPoint=CGPointMake(1,0);
UIView *v2=[[UIView alloc] initWithFrame:CGRectMake(50,50,200,300)];
v2.backgroundColor=[UIColor greenColor];
v2.layer.anchorPoint=CGPointMake(1, 0);
[self.view addSubview:v2];
[self.view addSubview:v];
我对这段代码的输出如下所示。
我看起来像红色视图输出的重叠绿色观点与两者具有相同的锚点,如下显示。
它可以帮助来形容什么是你的榜样发生的事情:
你把两个矩形的确切大小的屏幕上准确位置(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"];
添加了一个动画来说明:-) – 2012-07-21 13:40:40
你的意思是,你喜欢红色的观点是绿色的观点和红原视图之间的重叠面积的大小?
如果是这样,
v.frame = CGRectIntersection(v.frame, v2.frame);
我不想检查它是否相交。红色图像必须与彩色图像相交,并带有定位点(1,0) – andyPaul 2012-07-18 14:49:48
对不起andyPaul,你将不得不更清楚你想要什么。 CGRectInsersectsRect返回相交区域的CGRect。 – 2012-07-18 14:54:03
抱歉,您错了,请转到此链接https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html,CGRectIntersectsRect返回布尔 – andyPaul 2012-07-18 15:00:00
是上述代码中'frame'值的正确输出吗?这张照片上的“P(50.f,50.f)”在哪里?如果将'anchorPoint'行注释掉会导致什么结果? – holex 2012-07-18 15:36:10