iOS 裡最常被用到的 2D 變換工具就是 CGAffineTransform,它是一組 C 形式的函式,圍繞縮放、旋轉、平移三件事打轉。
// 縮放 CGAffineTransform CGAffineTransformScale(CGAffineTransform t, CGFloat sx, CGFloat sy); // 旋轉 CGAffineTransform CGAffineTransformRotate(CGAffineTransform t, CGFloat angle); // 平移 CGAffineTransform CGAffineTransformTranslate(CGAffineTransform t, CGFloat tx, CGFloat ty);
注意這三個函式的第一個參數都是「現有的 transform」,回傳值則是「套用完之後的 transform」。這正是串接多個變換的關鍵:把上一次的結果當成下一次的輸入。
建立一個 Empty Project,直接在 application 啟動方法裡搭一個簡單場景:一個紅色 view1,裡面放一個黃色 view2,再加一顆按鈕觸發變換。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(60, 100, 200, 200)];
view1.tag = 101;
view1.backgroundColor = [UIColor redColor];
[self.window addSubview:view1];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
view2.tag = 102;
view2.backgroundColor = [UIColor yellowColor];
[view1 addSubview:view2];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(110, 400, 100, 44)];
btn.backgroundColor = [UIColor cyanColor];
[btn addTarget:self action:@selector(onClick)
forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:btn];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)onClick {
UIView *view2 = [[self.window viewWithTag:101] viewWithTag:102];
view2.transform = CGAffineTransformScale(view2.transform, 0.8, 0.8);
view2.transform = CGAffineTransformRotate(view2.transform, 0.2);
view2.transform = CGAffineTransformTranslate(view2.transform, 50, 50);
}
上面這段把縮放、旋轉、平移依序串接。如果換個順序,最終位置會完全不同——矩陣相乘不可交換,這點在實務上很容易踩到。另外要記得:transform 改變的是「繪製方式」,frame 會跟著變動,但 center 與 bounds 的語意各自獨立,做布局計算時不要混用。
轉載請註明來自:https://blog.csdn.net/prevention