tig*_*ero 8 uiview contentmode ios5 uiview-hierarchy
根据UIView关于该contentMode物业的官方文件:
The content mode specifies how the cached bitmap of the view’s layer is adjusted when the view’s bounds change
Run Code Online (Sandbox Code Playgroud)
什么定义了这个定义中的内容?它是子视图还是我们为视图定义背景颜色时的示例.
我的第一个猜测是它应该至少应用于视图中的子视图,但是例如下面的代码片段在使用UIViewContentModeCenter标记时不会给我预期的结果 :
UIView* redView = [[UIView alloc] initWithFrame:CGRectMake(80, 80, 150, 200)];
redView.contentMode = UIViewContentModeCenter;
redView.backgroundColor = [UIColor redColor];
UIView* greenView = [[UIView alloc] initWithFrame:redView.bounds];
greenView.backgroundColor = [UIColor greenColor];
[redView addSubview:greenView];
redView.frame = CGRectInset(redView.frame, -5, -5);
[self.view addSubview:redView];
Run Code Online (Sandbox Code Playgroud)
我刚刚设置了一个包含greenView的redView.我还设置了redview的内容模式UIViewContentModeCenter- 为什么在我编写的代码中,当我更改其父级的框架时,greenView不居中?不应UIViewContentModeCenter该做什么?
谢谢你的澄清!
Ps:您可以在loadView简单的视图控制器模板项目中轻松测试上述代码.
第一次读到的内容模式 在这里
在您的示例中,您可以更改红色视图的框架.这将调用视图上的layoutSubviews,它将根据布局约束或自动调整蒙版重新定位绿色视图.你没有指定任何.所以绿色视图的框架将保持不变.
内容模式指定在调整大小时视图的图层应如何更新.根据内容模式,将调用drawRect.
您可以使用以下示例测试不同内容模式的效果:
添加一个UIView子类,使用此drawRect实现绘制一个圆:
- (void)drawRect:(CGRect)rect
{
// Drawing code
NSLog(@"drawRect %@", NSStringFromCGRect(rect));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, self.bounds);
[[UIColor redColor] setFill];
CGContextFillPath(ctx);
}
Run Code Online (Sandbox Code Playgroud)
在视图控制器中创建并添加圆视图:
CircleView* circleView = [[CircleView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
circleView.contentMode = UIViewContentModeCenter; // <- try different modes here
[self.view addSubview:circleView];
Run Code Online (Sandbox Code Playgroud)
现在让我们为框架设置动画,看看会发生什么:
dispatch_async(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:5 animations:^{
circleView.frame = CGRectMake(10, 10, 100, 200);
}];
});
Run Code Online (Sandbox Code Playgroud)
我正在以异步方式执行此操作以强制CoreGraphics至少使用原始帧绘制视图一次.如果不设置内容模式,最终会出现模糊的圆圈,因为它只是按比例放大而不重绘.UIViewContentModeCenter使小圆圈保持在中心 - 也不需要重绘.UIViewContentModeRedraw使视图再次使用新框架绘制视图.实际上,这是在动画开始之前发生的.
请注意,内容模式可能会影响绘图性能.
| 归档时间: |
|
| 查看次数: |
8424 次 |
| 最近记录: |