锚点anchorPoint

//

//  ViewController.m

//  UI-NO-36-2 锚点

//

//  Created by 容伟 on 15/9/15.

//  Copyright (c) 2015年 容伟. All rights reserved.

//

/*

 锚点: 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(0, 0, 100, 100);

    ship.position = self.view.center;

//    透明度 设置

    ship.opacity = 0.5;

    [self.view.layer addSublayer:ship];

    

    NSLog(@"锚点y:%f 锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x);

    

    

    APLayer = [[CALayer alloc] init];

    APLayer.bounds = CGRectMake(0, 0, 5, 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);

    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 锚点x:%f", ship.anchorPoint.y, ship.anchorPoint.x);

//    角度值经计算转化为幅度值。要把角度值转化为弧度制,可以使用一个简单的公式Mπ/180

    ship.transform = CATransform3DMakeRotation (90*M_PI/180, 0, 0, 1);

    

}

 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    ship.transform = CATransform3DIdentity;

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

原文地址:https://www.cnblogs.com/wukun16/p/4884164.html