【问题标题】:CALayer not rendering background color on devices, works in simulatorCALayer 不在设备上渲染背景颜色,在模拟器中工作
【发布时间】:2023-03-11 01:28:02
【问题描述】:

我已经从图层中创建了一个自定义按钮。我在init 中创建了一堆图层。一切都按预期工作,直到我去修改*它们。只有在实际设备上才会出现问题,在模拟器上代码按预期工作。

我尝试通过将 needsDisplay 和 needsLayout 设置为 YES 来强制渲染图层。

-(void) setBackgroundColor:(UIColor *)backgroundColor
{   
    //return; // if I return here, the button gets initialized with it's default royal blue color.  This works correctly on the simulator and device

    [primaryBackground setColors: [NSArray arrayWithObject:(id)backgroundColor.CGColor]];

    //return; //if I return here, primaryBackground will display a clear background on the device, but will display CGColor on the simulator.

    CALayer* ll = [CALayer layer];
    ll.frame=self.frame;
    ll.cornerRadius=primaryBackground.cornerRadius;
    [ll setBackgroundColor:backgroundColor.CGColor];
    [primaryBackground addSublayer:ll];

     //if I return here, primaryBackground will display the "expected" results on both platforms.  IE: it dispalys the new layer, but not it's background color.
}

模拟器

设备

测试

我在 iOS 5.1 和 4.2 上进行了测试,结果相同。在模拟器版本 4.1、4.2 和 5.1 上似乎工作相同

【问题讨论】:

  • 邮政编码或者它没有发生。
  • 还有什么版本的iOS设备和iOS模拟器。
  • 确保将图像导出为具有正常 RGB 配置文件的 .png。也许你有一个奇怪的颜色配置文件?!
  • 当我浏览并缩减代码时,我能够解决这个问题。我认为石板灰色与背景不同,但这只是一种视觉错觉 - 它是相同的颜色。 BG 颜色只是在设备方面被“擦除”了。
  • 您不应该将backgroundColor.CGColor 转换为(id) 吗? (id)backgroundColor.CGColor。只是也许。

标签: iphone ios core-animation calayer cagradientlayer


【解决方案1】:

我发现您的代码至少有 2 个问题:

  1. 每次更改颜色时,您都会添加一个新图层,而不会删除旧图层。首先,删除之前创建的子图层(或者只是更改其颜色而不创建和添加新子图层)。请记住,CALayer 的默认 opaque 属性设置为 NO,这意味着它正在与所有其他子图层混合。

    为什么还要添加另一个子层?在您的代码中,您完全覆盖了primaryBackgroundsetBackgroundColor: 函数不能像这样:

    - (void)setBackgroundColor:(UIColor *)backgroundColor { 
        [primaryBackground setBackgroundColor:backgroundColor.CGColor];
    }
    

    ?

  2. 1234563应该是ll.frame = self.bounds。您还应该覆盖- (void)layoutSubivews方法,并再次将背景层的frame设置为根层的边界。

请记住,在 iPhone Simulator 上,事物由不同的子系统渲染,并且比在真实设备上快得多。并且某些帧计算可能会重叠等。

【讨论】:

  • 我会尝试在 layoutSubviews 中设置大小,但据我所知,大小是我预期的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
相关资源
最近更新 更多