标签:
锚点: anchorPoint 以锚点为中心 执行动画 (与 渔夫固定船的点时一致的)
anchorPoint 默认是 0.5,0.5 (注意: 锚点 是一个比例)
anchorPoint 在左上角的时候 为 0,0
anchorPoint 在右上角的时候 为 1,0
anchorPoint 在左下角的时候 为 0,1
anchorPoint 在右下角的时候 为 1,1
1 #import "ViewController.h" 2 3 @interface ViewController () 4 { 5 CALayer *APLayer; 6 CALayer *ship; 7 } 8 @end 9 10 @implementation ViewController 11 12 - (void)viewDidLoad { 13 [super viewDidLoad]; 14 self.view.backgroundColor = [UIColor whiteColor]; 15 UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame]; 16 imageView.image = [UIImage imageNamed:@"网格.jpg"]; 17 [self.view addSubview:imageView]; 18 19 [self addShipLayer]; 20 21 } 22 23 - (void)addShipLayer { 24 25 ship = [[CALayer alloc] init]; 26 ship.backgroundColor = [UIColor brownColor].CGColor; 27 ship.bounds = CGRectMake(0, 0, 100, 100); 28 ship.position = self.view.center; 29 // 透明度 设置 30 ship.opacity = 0.5; 31 [self.view.layer addSublayer:ship]; 32 33 NSLog(@"锚点y:%f\n锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x); 34 35 36 APLayer = [[CALayer alloc] init]; 37 APLayer.bounds = CGRectMake(0, 0, 5, 5); 38 // 通过ship的尺寸 设置 APLayer 的中心点 39 // position.x = ship的宽*锚点的X position.y = ship的高*锚点的Y 40 CGFloat x = CGRectGetWidth(ship.bounds)*(ship.anchorPoint.x); 41 CGFloat y = CGRectGetHeight(ship.bounds)*(ship.anchorPoint.y); 42 APLayer.position = CGPointMake(x, y); 43 APLayer.backgroundColor = [UIColor cyanColor].CGColor; 44 [ship addSublayer:APLayer]; 45 } 46 47 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 48 UITouch *touch = [touches anyObject]; 49 CGPoint touchPoint = [touch locationInView:self.view]; 50 51 // 通过点击屏幕的x点/屏幕的宽度 得到点击的点 与屏幕一个比例 52 CGFloat x = touchPoint.x/CGRectGetWidth([UIScreen mainScreen].bounds); 53 // 通过点击屏幕的y点/屏幕的高度 得到点击的点 与屏幕一个比例 54 CGFloat y = touchPoint.y/CGRectGetHeight([UIScreen mainScreen].bounds); 55 // 改变ship 的锚点 56 ship.anchorPoint = CGPointMake(x, y); 57 58 59 CGFloat cx = CGRectGetWidth(ship.bounds)*ship.anchorPoint.x; 60 CGFloat cy = CGRectGetHeight(ship.bounds)*ship.anchorPoint.y; 61 APLayer.position = CGPointMake(cx, cy); 62 NSLog(@"锚点y:%f\n锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x); 63 // 角度值经计算转化为幅度值。要把角度值转化为弧度制,可以使用一个简单的公式Mπ/180 64 ship.transform = CATransform3DMakeRotation (90*M_PI/180, 0, 0, 1); 65 66 } 67 68 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 69 ship.transform = CATransform3DIdentity; 70 } 71 72 - (void)didReceiveMemoryWarning { 73 [super didReceiveMemoryWarning]; 74 // Dispose of any resources that can be recreated. 75 } 76 77 @end
标签:
原文地址:http://www.cnblogs.com/cnrong/p/4857275.html