iOS 技术点程序员iOS开发的正确姿势

iOS中的transfram属性(形变属性,实现视图的平移,缩放

2016-04-06  本文已影响5265人  Senior丶

在iOS中有个view有个属性transfram,翻译过来就是形变属性.通过transform属性可以修改对象的平移、缩放比例和旋转角度,在开发中一般用于做动画的.
话不多少,直接上代码:

//新建一个View;
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[tempView addSubview:[[UISwitch alloc] init]];
tempView.backgroundColor = [UIColor redColor];
[self.view addSubview:tempView];
self.tempView = tempView;
平移:CGAffineTransformMakeTranslation
缩放:CGAffineTransformMakeScale
旋转:CGAffineTransformMakeRotation

1.单纯视图的平移,旋转,缩放

// 平移(参数为X轴和Y轴的平移数)
self.tempView.transform = CGAffineTransformMakeTranslation(-100, 100);
// 旋转(参数为旋转角度)
self.tempView.transform = CGAffineTransformMakeRotation(-M_PI_4);
// 缩放(参数为X轴和Y轴的缩放比例)
self.tempView.transform = CGAffineTransformMakeScale(0.5, 0.5);

完全可以把这些放在动画中去
[UIView animateWithDuration:2.0 animations:^{
    self.tempView.transform = CGAffineTransformMakeTranslation(-100, 100);
}];

2.让视图边平移,边缩放,边旋转

//transform:形变属性,能完成的功能:平移、缩放、旋转
[UIView animateWithDuration:2.0 animations:^{
    CGAffineTransform translation = CGAffineTransformMakeTranslation(-100, 100);
   //在缩放基础上叠加平移
    CGAffineTransform scaleTranslation = CGAffineTransformScale(translation, 0.5, 0.5);
   //在旋转基础上叠加缩放和平移
    CGAffineTransform rotateScaleTranslation = CGAffineTransformRotate(scaleTranslation, M_PI_2);
    self.tempView.transform = rotateScaleTranslation;
}];

3.累计平移,缩放,旋转(例如每次点击按钮让视图旋转45°)

[UIView animateWithDuration:1.0 animations:^{
    //获取到上次旋转后transform来进行操作即可,平移,缩放同理
    self.tempView.transform = CGAffineTransformRotate(self.tempView.transform, M_PI_4);
}];

4.清空transform

 //清空transform,以前的平移、缩放、旋转都会消失
[UIView animateWithDuration:2.0 animations:^{
    self.tempView.transform = CGAffineTransformIdentity;
}];
上一篇下一篇

猜你喜欢

热点阅读