CGAffineTransform 定义
用于绘制2D图形的一个仿射变换矩阵。一个仿射变换矩阵用于做旋转、缩放、平移,一个仿射变换矩阵是一个3*3的矩阵,如下图

因为第三列一直是(0,0,1),所以CGAffineTransform 数据结构只包含前两列的值。
struct CGAffineTransform {
CGFloat a, b, c, d;
CGFloat tx, ty;
};
一个向量乘以3*3矩阵如下图

已知3*3的矩阵,下面的公式就是用于将点(x, y)转换成结果点 (x’,y’)的。

向量的变换
向量的平移
x方向移动tx,y方向移动ty

向量的缩放
x方向缩放sx,y方向缩放sy

向量的旋转
二维平面的向量旋转,即可表示为三维空间的向量绕Z轴的旋转,如图

将向量在平面内旋转角度B,假设向量的模为R,根据三角函数知识得

旋转后的向量为

用矩阵表达则为

CGAffineTransform 函数
CGAffineTransformIdentity
/* The identity transform: [ 1 0 0 1 0 0 ]. */
标准矩阵如下

CGAffineTransformMakeTranslation 函数
/* Return a transform which translates by `(tx, ty)':
t' = [ 1 0 0 1 tx ty ] */
CGAffineTransformMakeTranslation 是一个进行平移的方法,矩阵如下

CGAffineTransformMakeScale 函数
/* Return a transform which scales by `(sx, sy)':
t' = [ sx 0 0 sy 0 0 ] */
CGAffineTransformMakeScale 是一个进行缩放的方法,矩阵如下

CGAffineTransformMakeRotation 函数
/* Return a transform which rotates by `angle' radians:
t' = [ cos(angle) sin(angle) -sin(angle) cos(angle) 0 0 ] */
CGAffineTransformMakeRotation 是一个进行旋转的方法,矩阵如下

简单示例
效果图如下

点击平移(二维码图片x方向移动30,y方向移动30)效果如下

点击缩放(二维码图片x方向放大1.5倍,y方向放大1.5倍)效果如下

点击旋转(二维码图片旋转45°)效果如下

点击事件响应代码如下
#pragma mark - event response
- (void)segChanged:(UISegmentedControl *)segControl
{
if (segControl.selectedSegmentIndex == 0) {
self.qrCodeImgView.transform = CGAffineTransformIdentity;
} else if (segControl.selectedSegmentIndex == 1) {
self.qrCodeImgView.transform = CGAffineTransformIdentity;
[UIView animateWithDuration:0.3 animations:^{
self.qrCodeImgView.transform = CGAffineTransformMakeTranslation(30, 30);
}];
} else if (segControl.selectedSegmentIndex == 2) {
self.qrCodeImgView.transform = CGAffineTransformIdentity;
[UIView animateWithDuration:0.3 animations:^{
self.qrCodeImgView.transform = CGAffineTransformMakeScale(1.5, 1.5);
}];
} else if (segControl.selectedSegmentIndex == 3) {
self.qrCodeImgView.transform = CGAffineTransformIdentity;
[UIView animateWithDuration:0.3 animations:^{
self.qrCodeImgView.transform = CGAffineTransformMakeRotation(M_PI_4);
}];
}
}
CGAffineTransform 的介绍就到此结束啦...
网友评论