Ios5 UIViewContentMode所指的内容类型是什么?
根据UIView上关于Ios5 UIViewContentMode所指的内容类型是什么?,ios5,uiview,contentmode,uiview-hierarchy,Ios5,Uiview,Contentmode,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 这个定义中的内容是什么?例如,它是子视图还是定义了视图的背景色 我的第一个猜测是,它至少应该应用于视图中的子视图,但例如,在使用UIViewContentModeCenter标记时,下面的代码片段不会给出预期的结果
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的内容模式设置为UIViewContentModeCenter
——为什么在我编写的代码中,当我更改父视图的框架时,绿色视图不居中?UIViewContentModeCenter
不应该做什么
谢谢你的澄清
Ps:您可以在简单视图控制器模板项目的loadView
中轻松测试上述代码。首先阅读内容模式
在您的示例中,您更改了红色视图的帧。这将调用视图上的LayoutSubView,该视图将根据布局约束或自动调整大小遮罩重新定位绿色视图。您没有指定任何。因此,绿色视图的框架将保持不变
内容模式指定调整大小时视图的图层应如何更新。根据内容模式,是否调用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];
我异步地这样做是为了强制CoreGraphics使用原始帧至少绘制一次视图。
当你不设置内容模式时,你会得到一个模糊的圆圈,因为它只是放大而没有重画。UIViewContentModeCenter使小圆保持在中心-也无需重新绘制。UIViewContentModeRedraw使视图使用新框架再次绘制视图。实际上,这是在动画开始之前发生的
请注意,内容模式可能会影响图形性能
从文件中:
- (void)drawRect:(CGRect)rect
{
// Drawing code
NSLog(@"drawRect %@", NSStringFromCGRect(rect));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, self.bounds);
[[UIColor redColor] setFill];
CGContextFillPath(ctx);
}
内容模式指定如何缓存视图层的位图
在视图边界更改时调整
对于图像视图,这是关于图像的。为了一个观点
绘制其内容,这是指绘制的内容。是的
不影响子视图的布局
您需要查看子视图上的自动调整大小遮罩。
内容模式在这里是一个危险因素。如果你不能实现布局
您需要使用自动调整大小的掩码,然后需要实现
布局子视图并计算子视图位置和框架
手动
从jrturton的回答:通过调整帧,您肯定会重新绘制包含子视图的视图,该子视图设置为正在更改的帧边界?因此它不会保持居中,因为边界是相对于帧的?在使用边界作为框架的简单英语中,原点始终为0,0,并且具有匹配的宽度和高度