锚点: anchorPoint 以锚点为中心 执行动画 (与 渔夫固定船的点时一致的)
anchorPoint 默认是 0.5,0.5 (注意: 锚点 是一个比例)
anchorPoint 在左上角的时候 为 0,0
anchorPoint 在右上角的时候 为 1,0
anchorPoint 在左下角的时候 为 0,1
anchorPoint 在右下角的时候 为 1,1
#import "ViewController.h" @interface ViewController ()
{
CALayer *APLayer;
CALayer *ship;
}
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
imageView.image = [UIImage imageNamed:@"网格.jpg"];
[self.view addSubview:imageView]; [self addShipLayer]; } - (void)addShipLayer { ship = [[CALayer alloc] init];
ship.backgroundColor = [UIColor brownColor].CGColor;
ship.bounds = CGRectMake(, , , );
ship.position = self.view.center;
// 透明度 设置
ship.opacity = 0.5;
[self.view.layer addSublayer:ship]; NSLog(@"锚点y:%f\n锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x); APLayer = [[CALayer alloc] init];
APLayer.bounds = CGRectMake(, , , );
// 通过ship的尺寸 设置 APLayer 的中心点
// position.x = ship的宽*锚点的X position.y = ship的高*锚点的Y
CGFloat x = CGRectGetWidth(ship.bounds)*(ship.anchorPoint.x);
CGFloat y = CGRectGetHeight(ship.bounds)*(ship.anchorPoint.y);
APLayer.position = CGPointMake(x, y);
APLayer.backgroundColor = [UIColor cyanColor].CGColor;
[ship addSublayer:APLayer];
} - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view]; // 通过点击屏幕的x点/屏幕的宽度 得到点击的点 与屏幕一个比例
CGFloat x = touchPoint.x/CGRectGetWidth([UIScreen mainScreen].bounds);
// 通过点击屏幕的y点/屏幕的高度 得到点击的点 与屏幕一个比例
CGFloat y = touchPoint.y/CGRectGetHeight([UIScreen mainScreen].bounds);
// 改变ship 的锚点
ship.anchorPoint = CGPointMake(x, y); CGFloat cx = CGRectGetWidth(ship.bounds)*ship.anchorPoint.x;
CGFloat cy = CGRectGetHeight(ship.bounds)*ship.anchorPoint.y;
APLayer.position = CGPointMake(cx, cy);
NSLog(@"锚点y:%f\n锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x);
// 角度值经计算转化为幅度值。要把角度值转化为弧度制,可以使用一个简单的公式Mπ/180
ship.transform = CATransform3DMakeRotation (*M_PI/, , , ); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
ship.transform = CATransform3DIdentity;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end