简体   繁体   English

设备旋转期间CALayer子层不正常

[英]CALayer sublayer not graceful during device rotation

I drew a circle directly on a view's layer, a device rotation looks perfect. 我直接在视图的图层上绘制了一个圆圈,设备旋转看起来很完美。

The drawing occurs in the func draw(_ rect: CGRect) method. 绘制以func draw(_ rect: CGRect)方法进行。

I then drew the circle on a sublayer and added it to the view in the init method. 然后,我在子层上绘制了圆圈并将其添加到init方法的视图中。

I update the sub layer's frame in the func draw(_ rect: CGRect) method. 我使用func draw(_ rect: CGRect)方法更新子图层的框架。

It seems to me like there are times that the sublayer is being updated before the device rotation is complete. 在我看来,有时需要在设备旋转完成之前更新子层。 Hence the first image below. 因此,下面的第一张图片。

A quick fix to make this look a bit better is to clip the subview layers. 一种使外观更好的快速修复方法是裁剪子视图图层。 This way the circle won't bleed to the main view (orange view). 这样,圆不会流到主视图(橙色视图)。

Although this isn't fixing the main issue. 尽管这不能解决主要问题。 I don't know why adding a sublayer is causing this issue. 我不知道为什么添加子层会导致此问题。

I'm also drawing the content of the sublayer in the draw method of it's super view. 我还在超级视图的draw方法中绘制子层的内容。 The orange view is not the super view, the super view is the rectangle in the middle 橙色视图不是超级视图,超级视图是中间的矩形

During Rotation 旋转期间

旋转期间

在此处输入图片说明

Note: I did not add example code because all examples that I have seen have the same issue. 注意:我没有添加示例代码,因为我看到的所有示例都存在相同的问题。 Others fix this by hardcoding the size of a view, hence the rotation will not resize the view and the rotation will not cause this. 其他人则通过对视图的大小进行硬编码来解决此问题,因此旋转不会调整视图的大小,并且旋转不会导致这种情况。 They also, tend to lock the view in portrait mode. 他们还倾向于将视图锁定为纵向模式。

Although, if the example code is needed I can create a simple example. 虽然,如果需要示例代码,我可以创建一个简单的示例。

I found a solution to the issue. 我找到了解决该问题的方法。

It seems to me like everyone else has the same issues. 在我看来,就像其他所有人一样,都有同样的问题。 This is because layers don't have constraints. 这是因为图层没有约束。

We don't see these issues on production apps because apps are usually locked in portrait mode. 我们不会在生产应用程序上看到这些问题,因为应用程序通常被锁定为纵向模式。 It also seems like apple tends to use images for their controls and avoids drawing. 苹果似乎也倾向于使用图像作为控件并避免绘制。 This is according to a Ray Wenderlich article that I read. 这是根据我阅读的Ray Wenderlich 文章得出的。


The solution is basically to use subviews (instead of sublayers) and use the layer built into the sub view to draw. 解决方案基本上是使用子视图(而不是子图层),并使用子视图中内置的图层进行绘制。

This article explains the process: https://marcosantadev.com/calayer-auto-layout-swift/ 本文介绍了该过程: https : //marcosantadev.com/calayer-auto-layout-swift/

Here is an image showing the rotation with a subview and sublayers. 这是显示带有子视图和子图层的旋转的图像。 The subview gracefully rotates because it has constraints. 子视图由于存在约束而可以正常旋转。 在此处输入图片说明

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

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