试图理解UIView和CALayer之间的关系。我阅读了Apple文档,但它没有详细描述两者之间的关系。
为什么当我添加背景图像来查看“自定义 ViewController.view”时,我会得到不需要的图像黑色。
当我将背景图像添加到“customViewController.view.layer”层时,图像的黑色区域消失了(这就是我想要的),但背景图像被颠倒了。这是为什么?
如果我要添加标签/视图/按钮/等。对于视图,图层的背景图像是否会遮挡它们,因为 CAlayer 是由 UIView 支持的?
-
当您设置 UIView 的背景颜色时,它是否会自动设置关联图层的背景颜色?
- (void)viewDidLoad
{
[super viewDidLoad];
customViewController = [[CustomViewController alloc] init];
customViewController.view.frame = CGRectMake(213, 300, 355, 315);
customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]];
// customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor;
[self.view addSubview:customViewController.view];
}
视图中的背景图片:
- (void)viewDidLoad
{
[super viewDidLoad];
customViewController = [[CustomViewController alloc] init];
customViewController.view.frame = CGRectMake(213, 300, 355, 315);
// customViewController.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]];
customViewController.view.layer.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"login_background.png"]].CGColor;
[self.view addSubview:customViewController.view];
}
view.layer中的背景图片:
UIView 默认创建为不透明。当您将backgroundColor 设置为具有透明度的图案时,它会选择黑色作为背景色。您可以设置customViewController.view.opaque = NO;
让您身后的景色的背景显现出来。
当您将图层的背景颜色设置为具有透明度的图案时,您将绕过 UIView 逻辑,因此视图的不透明性将被忽略; UIView 的变换也是如此。 CoreGraphics 和朋友使用正 y 轴指向上方的坐标系。 UIKit 翻转这个坐标系。这就是图像看起来颠倒的原因。
如果您添加标签/视图/按钮/等。将正确显示在图层背景图案的顶部。
当您设置视图的背景颜色时,看起来就像确实设置了图层的背景颜色一样。 (我没有在任何地方看到过这个记录)。
本质上,UIKit 的 UIView 东西是一个高级界面,最终渲染到层上。
希望这可以帮助。
编辑 2011 年 5 月 7 日
您可以通过翻转图层的坐标系来使图像以正确的方式显示,但您不应该对 view.layer 执行此操作; UIKit 不希望你弄乱这个层,所以如果你翻转它的坐标系,任何 UIKit 绘图都会被翻转;你需要使用一个子层。
所以你的代码看起来像这样:
- (void)viewDidLoad
{
[super viewDidLoad];
customViewController = [[CustomViewController alloc] init];
customViewController.view.frame = CGRectMake(213, 300, 355, 315);
CALayer* l = [CALayer layer];
l.frame = customViewController.bounds;
CGAffineTransform t = CGAffineTransformMake(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
l.affineTransform = t;
l.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage
imageNamed:@"login_background.png"]].CGColor;
[customViewController.view.layer addSublayer:l];
[self.view addSubview:customViewController.view];
}
注意:通常,当您翻转坐标时,您会包含高度。对于图层,您不需要这样做。我还没有深究为什么会这样。
正如您所看到的,这里涉及更多的代码,而且这样做并没有真正的优势。我强烈建议您坚持使用 UIKit 方法。我发布代码只是为了满足您的好奇心。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)