【深入 iOS 开发】iOS 仿射变换和 3D 变换

2D仿射变换

UIView的transform属性是一个CGAffineTransform类型,用于在二维空间做旋转,缩放和平移。CGAffineTransform是一个可以和二维空间向量(例如CGPoint)做乘法的3X2的矩阵:

《【深入 iOS 开发】iOS 仿射变换和 3D 变换》

Paste_Image.png

当对UIView应用变换矩阵,UIView图层矩形内的每一个点都被相应地做变换,从而形成一个新的四边形的形状。CGAffineTransform中的“仿射”的意思是无论变换矩阵用什么值,图层中平行的两条线在变换之后任然保持平行.

单位矩阵

CGAffineTransformIdentity

CGAffineTransform transform = CGAffineTransformIdentity; 结果: (CGAffineTransform) transform = (a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0)

创建仿射变换矩阵

CGAffineTransformMakeRotation(CGFloat angle) // 旋转 CGAffineTransformMakeScale(CGFloat sx, CGFloat sy) // 缩放 CGAffineTransformMakeTranslation(CGFloat tx, CGFloat ty) // 平移
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_4); 结果 : (CGAffineTransform) transform = (a = 0.70710678118654757, b = 0.70710678118654746, c = -0.70710678118654746, d = 0.70710678118654757, tx = 0, ty = 0)
CGAffineTransform transform = CGAffineTransformMakeScale(0.8, 0.8); 结果: (CGAffineTransform) transform = (a = 0.80000000000000004, b = 0, c = 0, d = 0.80000000000000004, tx = 0, ty = 0)
CGAffineTransform transform = CGAffineTransformMakeTranslation(10, 10); 结果: (CGAffineTransform) transform = (a = 1, b = 0, c = 0, d = 1, tx = 10, ty = 10)

《【深入 iOS 开发】iOS 仿射变换和 3D 变换》

Paste_Image.png

图中,灰色为旧图,蓝色为变化后的新图.

修改仿射变换矩阵

CGAffineTransformRotate(CGAffineTransform t, CGFloat angle) // 在矩阵t上添加旋转效果 CGAffineTransformScale(CGAffineTransform t, CGFloat sx, CGFloat sy) // 在矩阵t上添加缩放效果 CGAffineTransformTranslate(CGAffineTransform t, CGFloat tx, CGFloat ty) // 在矩阵t上添加平移效果
 //create a new transform CGAffineTransform transform = CGAffineTransformIdentity; //scale by 50% transform = CGAffineTransformScale(transform, 0.5, 0.5); //rotate by 30 degrees transform = CGAffineTransformRotate(transform, M_PI / 180.0 * 30.0); //translate by 200 points transform = CGAffineTransformTranslate(transform, 200, 0); //apply transform to layer self.layerView.layer.affineTransform = transform;

zsisme.gitbooks.io/ios-/conten…

3D变换

CATransform3D可以让视图在3D空间内移动或者旋转.和CGAffineTransform类似,CATransform3D也是一个矩阵,但是和2×3的矩阵不同,CATransform3D是一个可以在3维空间内做变换的4×4的矩阵.

这里讲的很好:
zsisme.gitbooks.io/ios-/conten…
tech.imdada.cn/2016/06/21/…

    原文作者:小蜜蜂
    原文地址: https://juejin.im/entry/58a29c692f301e00690690c5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞