锚点

/*
 anchorPoint 锚点(是一个比例)  以锚点为中心执行动画  (与 渔夫 固定船的 一致)
 anchorPoint 默认是0.5 0.5  
 anchorPoint 在左上角的时候为 (0,0)在右上角为(1,0) 在左下角为(0,1)  在右下角为(1,1)
 
 
 
 */


#import "ViewController.h"

@interface ViewController ()
{
    CALayer *ship;
    CALayer *APLayer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
    imageView.image = [UIImage imageNamed:@"网格图"];
    [self.view addSubview:imageView];
    
    [self shipLayer];
    
}

- (void)shipLayer{
    ship = [[CALayer alloc]init];
    ship.backgroundColor = [UIColor purpleColor].CGColor;
    ship.bounds = CGRectMake(0, 0, 10, 100);
    ship.position = self.view.center;
//    opacity设置CALayer的透明度
    ship.opacity = 0.7;
    [self.view.layer addSublayer:ship];
    NSLog(@"x %f,y %f",ship.anchorPoint.x,ship.anchorPoint.y);
    
    APLayer = [[CALayer alloc]init];
    APLayer.bounds = CGRectMake(0, 0, 10, 10);
    APLayer.backgroundColor = [UIColor redColor].CGColor;
    APLayer.cornerRadius = 5;
//    通过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);
    [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(@"x %f,y %f",ship.anchorPoint.x,ship.anchorPoint.y);
    
//    角度值经计算转化为弧度值。要把角度值转化为弧度值,可以使用一个简单的公式Mπ/180
//    x y z 是三个轴 要围绕谁去旋转就将谁设置为1,其余为0
    ship.transform = CATransform3DMakeRotation(180*M_PI/180,0 , 0, 1);
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    ship.transform = CATransform3DIdentity;
}
原文地址:https://www.cnblogs.com/liYongJun0526/p/4874135.html