根据UIView上关于contentMode属性的官方文档:
The content mode specifies how the cached bitmap of the view’s layer is adjusted when the view’s bounds change定义中的内容是什么?它是一个子视图,还是当我们定义了一个视图的背景颜色,例如。
我最初的猜测是,它应该至少适用于视图中的子视图,但例如,在使用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];我刚刚设置了一个redView,其中将包含一个greenView。我还将redview的内容模式设置为UIViewContentModeCenter --为什么在我编写的代码中,当我更改其父视图的框架时,greenView没有居中?难道UIViewContentModeCenter不应该这么做吗?
谢谢你的澄清!
Ps:您可以轻松地在简单视图控制器模板项目的loadView中测试上述代码。
发布于 2013-03-28 06:27:05
从文件中: 内容模式指定当视图的边界发生变化时如何调整视图层的缓存位图。 对于图像视图,这里讨论的是图像。对于绘制其内容的视图,这是在讨论绘制的内容。它不影响子视图的布局。 您需要查看子视图上的自动调整掩码。内容模式在这里是一条红鲱鱼。如果无法实现需要使用自动调整掩码的布局,则需要实现layoutSubviews并手动计算子视图位置和帧。
从jrturton的答案到:https://stackoverflow.com/a/14111480/1374512
发布于 2012-10-20 13:18:41
第一读内容模式这里
在您的示例中,您更改了红色视图的框架。这将调用视图上的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);
}在视图控制器中,创建并添加圆形视图:
CircleView* circleView = [[CircleView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
circleView.contentMode = UIViewContentModeCenter; // <- try different modes here
[self.view addSubview:circleView];现在让我们对框架进行动画化,看看会发生什么:
dispatch_async(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:5 animations:^{
circleView.frame = CGRectMake(10, 10, 100, 200);
}];
});我异步地这样做是为了迫使CoreGraphics至少用原始帧绘制视图一次。当您不设置内容模式时,就会出现一个模糊的循环,因为它只是缩放而不重画。UIViewContentModeCenter使小圆圈停留在中心-也不需要重绘。UIViewContentModeRedraw使视图再次使用新框架绘制视图。实际上,这是在动画开始之前发生的。
请注意,内容模式可能会影响绘图性能。
https://stackoverflow.com/questions/12827710
复制相似问题