繁体   English   中英

关于iOS背景图像的UIVIew和CALayer之间的关系

[英]Relationship between UIVIew and CALayer regarding background image on iOS

试图了解UIView和CALayer之间的关系。 我阅读了Apple文档,但没有详细描述两者之间的关系。

  1. 为什么当我添加背景图像来查看“customViewController.view”时,我得到图像的不需要的黑色。

  2. 当我将背景图像添加到图层“customViewController.view.layer”时,图像的黑色区域消失了(这就是我想要的),但背景图像是颠倒翻转的。 这是为什么?

  3. 如果我要添加标签/视图/按钮/等。 对于视图,图层的背景图像是否会阻止它们,因为CAlayer由UIView支持?

  4. 当您设置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中的背景图像:

图层中的背景图片

  1. UIView默认情况下创建为opaque。 将backgroundColor设置为具有透明度的图案时,选择黑色作为背景颜色。 你可以设置customViewController.view.opaque = NO; 允许你背后的视图背景显示出来。

  2. 当您将图层的backgroundColor设置为具有透明度的图案时,您将绕过UIView逻辑,因此忽略视图的不透明度; UIView的改造也是如此。 CoreGraphics和朋友使用坐标系统,其中正y轴指向上方。 UIKit翻转了这个坐标系。 这就是图像颠倒的原因。

  3. 如果你添加标签/视图/按钮/等。 将在图层的背景图案顶部正确显示。

  4. 设置视图的背景颜色时,看起来好像设置了图层的背景颜色。 (我没有在任何地方看到这个记录)。

基本上UIKit的UIView东西是一个高级界面,最终渲染到图层上。

希望这可以帮助。

编辑2011年5月7日

你可以通过翻转图层的坐标系来让图像显示正确的方向但是你不应该这样做来查看。 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方法。 我只是发布了代码以回应你的好奇心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM