[英]Rotating UIView including the CALayer bounds AND the CALayer frame
我想使用UIDeviceOrientationDidChangeNotification
旋轉我的“containerView”UIView(截圖中的半透明紅色框),然后稍后(在它旋轉之后)將子圖層添加到視圖的圖層,但我發現只調整了containerView.layer的邊界大小,而不是containerView.layer的框架! :(
這是它在肖像中的樣子:
示例代碼:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidAppear:(BOOL)animated
{
CALayer *r = [CALayer layer];
r.frame = CGRectMake(0, 0, 100, 100);
r.contents = (id)[[UIImage imageNamed:@"r.png"] CGImage];
[self.containerView.layer addSublayer:r];
}
- (void)deviceRotated:(NSNotification *)notification
{
...
if (orientation == UIDeviceOrientationLandscapeLeft) {
self.containerView.transform = CGAffineTransformMakeRotation(RADIANS(90));
self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);
NSLog(@"container bounds: %@", NSStringFromCGRect(self.containerView.bounds));
NSLog(@"container layer frame: %@", NSStringFromCGRect(self.containerView.layer.frame));
NSLog(@"container layer bounds: %@", NSStringFromCGRect(self.containerView.layer.bounds));
CALayer *testLayer = [CALayer layer];
testLayer.backgroundColor = [[UIColor blueColor] CGColor];
testLayer.bounds = self.containerView.layer.frame;
testLayer.position = CGPointMake(CGRectGetMidX(testLayer.bounds), CGRectGetMidY(testLayer.bounds));
[self.containerView.layer addSublayer:testLayer];
}
}
旋轉后打印:
container bounds: {{0, 0}, {411, 320}}
container layer frame: {{0, 0}, {320, 411}}
container layer bounds: {{0, 0}, {411, 320}}
(注意圖層的幀仍然是320寬,411高。)
所以現在它看起來像:
我也嘗試在更改邊界之前設置中心,但看起來像:
我知道containerView的圖層沒有自動調整大小,所以我嘗試在變換后設置圖層的框架... self.containerView.layer.frame = self.containerView.bounds;
然后打印出來:
container bounds: {{0, 0}, {320, 411}}
container layer frame: {{0, 0}, {411, 320}}
container layer bounds: {{0, 0}, {320, 411}}
看起來像:
哎呀!
所有視圖的autoResizesSubviews都設置為YES,clipsToBounds設置為NO。 我不能使用shouldAutorotateToInterfaceOrientation
因為真正的應用程序將有一個相機預覽,所以我希望根視圖保持縱向。
我必須錯過一些關於我如何在containerView上進行轉換以使其圖層的邊界和框架相同的東西,但我無法弄清楚它是什么! 任何幫助將非常感激。
更新 - 修正:
設置新添加圖層邊界( testLayer.bounds
)到contentView.layer.bounds
代替contentView.layer.frame
的伎倆。 (因為轉換contentView會使其layer.frame失效。)謝謝邁克爾!
固定:
self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);
由於翻轉的上下文,您在此處的設置是錯誤的。 您將其設置為寬,因為它翻轉90度后會回到垂直狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.