效果图如下:
我们可以看到,不管棕色的方块怎么运动,总是以绿色的店作为中心来移动的,这就和船只的锚点是一样的道理
一、简介:
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;
}