標籤:style blog http io os ar 使用 for sp
圍繞底邊中點旋轉
UIView本身是支援旋轉的,可以用UIView.transform屬性實現旋轉。
The origin of the transform is the value of the center property, or the layer’s anchorPoint property if it was changed.
這個旋轉預設是圍繞這UIView.center或者UIView.layer.anchorPoint旋轉的。似乎UIView.layer.anchorPoint屬性給了我們一個能實現圍繞任意點旋轉的可能,事實上也確實能夠通過UIView.layer.anchorPoint實現圍繞任意點旋轉。
囿於UIView.layer.anchorPoint屬性的複雜性、關聯性太強(參考http://www.cnblogs.com/benbenzhu/p/3615516.html),我嘗試從其他方向入手。
幸運的是,這問題在數學上早已解決(不應這麼說,因果弄反了,數學上解決後,電腦才應用),就是用仿射矩陣轉換。
圍繞任意點旋轉的仿射矩陣如下(摘自百度百科):
靶心圖表形以(x, y)為軸心逆時針旋轉theta弧度,變換矩陣為:[ cos(theta) -sin(theta) x-x*cos+y*sin][ sin(theta) cos(theta) y-x*sin-y*cos ][ 0 0 1 ]相當於兩次平移變換與一次原點旋轉變換的複合:[1 0 x] [cos(theta) -sin(theta) 0] [1 0- x][0 1 y] [sin(theta) cos(theta) 0] [0 1 -y][0 0 1] [ 0 0 1] [0 0 1]這裡是以空間任一點為圓心旋轉的情況。
可以直接使用上面第一個公式計算放射矩陣;
我根據上面第二個等效公式和ios的API,歸納出下面函數,用於計算仿射矩陣,實現圍繞UIView的座標系的任意點旋轉。
CGAffineTransform GetCGAffineTransformRotateAroundPoint(float centerX, float centerY float x ,float y ,float angle){ x = x - centerX; //計算(x,y)從(0,0)為原點的座標系變換到(CenterX ,CenterY)為原點的座標系下的座標 y = y - centerY; //(0,0)座標系的右橫軸、下豎軸是正軸,(CenterX,CenterY)座標系的正軸也一樣 CGAffineTransform trans = CGAffineTransformMakeTranslation(x, y); trans = CGAffineTransformRotate(trans,angle); trans = CGAffineTransformTranslate(trans,-x, -y); return trans;}其中(centerX,centerY)是UIView.center屬性值.需要注意的是每次設定UIView.transform時,最好先設定為CGAffineTransformIdentity以恢複UIView為初始視圖,否則會有意想不到的效果
示意代碼
UIView *view = ......float centerX = view.bounds.size.width/2;float centerY = view.bounds.size.height/2;float x = view.bounds.size.width/2;float y = view.bounds.size.height;CGAffineTransform trans = GetCGAffineTransformRotateAroundPoint(centerX,centerY ,45.0/180.0*M_PI);view.transform = CGAffineTransformIdentity;view.transform = trans;
IOS 以任意點為圓心 旋轉UIView