它可以幫助來形容什麼是你的榜樣發生的事情:
你把兩個矩形的確切大小的屏幕上準確位置(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