您的位置:首页 > 其它

CGAffineTransformMakeTranslation和CGAffineTransformTranslate

2016-04-01 10:10 483 查看
CGAffineTransformMakeTranslation : 每次都是以最初位置的中心点为参考

CGAffineTransformTranslate 每次都是以传入的transform为参照(既 有叠加效果)

这两个动画属性属于视图的平移属性,不会改变视图的大小,只会通过平移将视图的位置改变,是一种相对位置的改变,例如下代码:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:imageView];
self.imageView = imageView;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 300, 50, 30);
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
button.backgroundColor = [UIColor orangeColor];
button.selected = NO;

UIButton *buttonn = [UIButton buttonWithType:UIButtonTypeCustom];
buttonn.frame = CGRectMake(200, 300, 50, 30);
[buttonn addTarget:self action:@selector(buttonnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonn];
buttonn.backgroundColor = [UIColor orangeColor];
buttonn.selected = NO;

}


这段代码是通过CGAffineTransformMakeTranslation来对视图进行平移,通过运行代码后可以看到,小方块移动到了距离起始位置的(50,0),然后再点击按钮,又回到了基于起始位置的(0,0)点

- (void)buttonClick:(UIButton *)btn{

if (btn.isSelected) {
btn.selected = NO;
//通过平移,回到当前视图相对于frame的(0,0)位置
self.imageView.transform = CGAffineTransformMakeTranslation(0,0);
}else {
btn.selected = YES;

//通过平移,平移到当前视图相对于frame的(0,50)位置
[UIView animateWithDuration:5 animations:^{
self.imageView.transform = CGAffineTransformMakeTranslation(0,50);
}];
}
}


这段代码运行效果和上一段代码的效果是相同的,但是代码有区别,是通过CGAffineTransformTranslate动画来实现的,其中要求传入三个参数,第一个参数是基于哪个位置的CGAffineTransform,其中CGAffineTransformIdentity是最初位置的中心点,也就是设置frame的位置,每次改变都是基于这个中心点进行改变,当我们传入某一个视图的transform时,相当于是在每一移动的过程中都在不断的修改视图的transform,因此点击按钮的时候回不停的移动,后面的第二个,第三个参数要求传入的是平移的x,y坐标

CGAffineTransformMakeTranslation只需要传入2个参数即可实现平移和回到原来位置,可以想象成为其默认带入一个CGAffineTransformIdentity的参数,因为当我CGAffineTransformTranslate对视图不断平移后,在通过CGAffineTransformMakeTranslation回到(0.0)点,是回到的视图最初位置的中心点

- (void)buttonnClick:(UIButton *)btn {

if (btn.isSelected) {
btn.selected = NO;

self.imageView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
}else {
btn.selected = YES;
[UIView animateWithDuration:5 animations:^{
self.imageView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 50);
}];
}
}


执行代码效果去如下:其中我将CGAffineTransformIdentity参数修改为self.imageView.transform后的效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动画 CGAffine