效果圖如下:
我們可以看到,不管棕色的方塊怎麼運動,總是以綠色的店作爲中心來移動的,這就和船隻的錨點是一樣的道理
一、簡介:
anchorPoint 錨點 以錨點爲中心,執行動畫(與漁夫固定船的點一致)
anchorPoint 默認是 0.5 0.5 錨點是一個比例
anchorPoint 錨點在左上角的時候,爲(0,0) 右上角(1,0)左下角(0,1) 右下角(1,1)
二、代碼
1、定義兩個全局變量
<span style="color:#009900;">{
CALayer *ship;
CALayer *APLayer;
}</span>
ship = [[CALayer alloc]init];
ship.backgroundColor = [UIColor brownColor].CGColor;
ship.bounds = CGRectMake(0, 0, 100, 100);
ship.position = self.view.center; // CALayer的 中心點
ship.opacity = 0.5; // CALayer的透明度 shadowOpacity
NSLog(@"錨點x:%f 錨點y:%f",ship.anchorPoint.x,ship.anchorPoint.y);
[self.view.layer addSublayer:ship];
APLayer = [[CALayer alloc]init];
APLayer.backgroundColor = [UIColor greenColor].CGColor;
APLayer.bounds = CGRectMake(0, 0, 10, 10);
CGFloat x = CGRectGetWidth(ship.bounds)*ship.anchorPoint.x;
CGFloat y = CGRectGetHeight(ship.bounds)*ship.anchorPoint.y;
APLayer.position = CGPointMake(x, y);
[ship addSublayer:APLayer];
3、觸摸屏幕和觸屏結束調用
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
// APLayer.position = touchPoint;
// 得到錨點
CGFloat x1 = touchPoint.x/CGRectGetWidth(self.view.frame);
CGFloat y1 = touchPoint.y/CGRectGetHeight(self.view.frame);
ship.anchorPoint = CGPointMake(x1, y1);
NSLog(@"%f %f",x1,y1);
// 得到APlayer的位置
CGFloat x = CGRectGetWidth(ship.bounds)*ship.anchorPoint.x;
CGFloat y = CGRectGetHeight(ship.bounds)*ship.anchorPoint.y;
APLayer.position = CGPointMake(x, y);
// 角度值經計算轉化爲弧度值。要把角度值轉化爲弧度值,可以使用一個簡單的公式Mπ/180
// xyz 是三個軸 0 1
ship.transform = CATransform3DMakeRotation(45*M_PI/180, 0, 0, 1);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
ship.transform = CATransform3DIdentity;
}