iphone - 绘制层 :inContext is not called

标签 iphone core-animation core-graphics

我有自己的最小 View 类:

- (void) awakeFromNib
{
    NSLog(@"awakeFromNib!");
    [self.layer setDelegate:self];
    [self.layer setFrame:CGRectMake(30, 30, 250, 250)];
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 5.0;
    self.layer.backgroundColor = [[UIColor redColor] CGColor];
    [self setNeedsDisplay];
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    NSLog(@"drawing!");
}

drawLayer:inContext 永远不会被调用,尽管我可以将图层视为红色圆角矩形。我错过了什么?

编辑:来自苹果文档

You can draw content for your layer, or better encapsulate setting the layer’s content image by creating a delegate class that implements one of the following methods: displayLayer: or drawLayer:inContext:.

Implementing a delegate method to draw the content does not automatically cause the layer to draw using that implementation. Instead, you must explicitly tell a layer instance to re-cache the content, either by sending it a setNeedsDisplay or setNeedsDisplayInRect: message, or by setting its needsDisplayOnBoundsChange property to YES.

还有

drawLayer:inContext:

If defined, called by the default implementation of drawInContext:.

最佳答案

您永远不应该更改 UIView 层的委托(delegate)。来自 UIView 图层属性的文档:

Warning: Since the view is the layer’s delegate, you should never set the view as a delegate of another CALayer object. Additionally, you should never change the delegate of this layer.

如果你想在 View 中进行自定义绘图,只需重写drawRect:方法即可。

如果您确实想使用图层,则需要创建自己的图层:

UIView *myView = ...
CALayer *myLayer = [CALayer layer];
myLayer.delegate = self;
[myView.layer addSublayer:myLayer];

在这两种情况下,您都需要在第一种情况下在 View 上调用 setNeedsDisplay,在第二种情况下在自定义图层上调用 setNeedsDisplay。你永远不会直接调用drawRect:或drawLayer:inContext:,它们会在你调用setNeedsDisplay时自动调用。

关于iphone - 绘制层 :inContext is not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4033811/

相关文章:

ios - UIScrollView 在横向模式下不滚动 - 附上测试代码和屏幕截图

ios - 动画 CIFilter CIPerspectiveCorrection

iphone - 拥有一个包含许多子层的 CALayer。当在子图层上调用 setNeedsDisplay 时,我收到无效上下文错误

ios - 代码 : compositing with alpha using core image

ios - 在这种情况下我应该避免单例吗?

iphone - 核心数据 - 监视更改并注册本地通知

iphone - iPhone 横屏时如何调用另一个 View

ios - 持续时间导致访问错误问题的 UIView 动画

swift - 如何防止CALayer绘制背景色?

ios - CGRectApplyAffineTransform 和实际 View 的框架