iphone - addSublayer 和 renderInContext 在 iOS 中如何工作

标签 iphone ios5 calayer render

当我按照以下方式编写代码时..

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(context, kCGBlendModeDifference);

    sublayer = [CALayer layer];
    sublayer.backgroundColor = [UIColor redColor].CGColor;
    sublayer.opaque = NO;
    sublayer.frame = CGRectMake(30, 30, 250, 200);
    [sublayer renderInContext:context];

    sublayer1 = [CALayer layer];
    sublayer1.opaque = NO;
    sublayer1.backgroundColor = [UIColor greenColor].CGColor;
    sublayer1.frame = CGRectMake(120, 120, 100, 250);
    [sublayer1 renderInContext:context];

}

我得到的第一张图片如下

enter image description here enter image description here

子层、子层1的位置不正确,因为我已经为它们设置了框架。它们的交集是混合颜色。为什么他们不设置实际位置?

但是当我使用addSublayer时,我得到了上面第二张图片。这里子层、子层1的位置是正确的。它们的交集不是混合颜色。就这样发生了什么事。

为什么我创建子图层是,当我拖动子图层时,它们的相交部分必须是混合颜色。请任何人给我解释一下。

提前致谢。

最佳答案

这就是代码中发生的情况:在第一种情况下,您只是在 View 底层的图形上下文中绘制图层。这就是drawRect 的作用。框架的原点不会影响这一点,因为它只是将子图层放置在其父图层内。但在这里,该图层永远不会添加到父图层中,因此原点根本不执行任何操作,并且两个形状都出现在 0, 0 处。

在第二种情况下,首先发生与之前完全相同的事情,但是因为您还将图层添加到图层层次结构中,所以它们在 View 底层的指定位置再次呈现。每个子图层都在其自己的上下文中渲染,因此您在drawRect中设置的混合模式对它们没有影响。

实际上,如果您只想获取两个矩形的图像,则根本不需要子图层。您可以直接在 View 底层的drawRect中绘制它们:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetBlendMode(ctx, kCGBlendModeDifference);

    CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor);
    CGRect rect1 = CGRectMake(30, 30, 250, 200);
    CGContextFillRect(ctx, rect1);

    CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor);
    CGRect rect2 = CGRectMake(120, 120, 100, 250);
    CGContextFillRect(ctx, rect2);
}

编辑(因为问题已被编辑):

您可以使用这种方法来拖动图层,如下所示:

  • 使用上述混合模式和绘图命令,在新图层或其上方的 View 上为每个移动图层绘制一个矩形
  • 使用移动图层的当前帧来绘制矩形
  • 确保新的顶层不会受到触摸
  • 只要交互图层的位置发生更改,就重新绘制新图层

关于iphone - addSublayer 和 renderInContext 在 iOS 中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11396541/

相关文章:

javascript - 检测 Javascript 中是否启用了运动和方向访问 - iOS

ios - 无法在 bundle 中找到名为 'Main' 的 Storyboard,Xcode 7

ios - 归档时出现以前不存在的奇怪的新错误

iphone - Core Data的NSPrivateQueueConcurrencyType以及线程间共享对象

ios - 如何在 iOS 的 CALayer 中显示彩色图像?

objective-c - OS X 上的 CATiledLayers

iphone - 在 iphone 中使用 Brautaset Json 框架时出错

iphone - 最佳方法 : Read And Understand Unknown Xcode Projects

ios - 如何使用 iOS5 的 viewcontroller 创建通用 View ?

objective-c - 突出显示 PDF - iOS