3

我正在绘制一个形状,CALayer如下-(void)drawInContext:(CGContextRef)ctx所示:

UIGraphicsPushContext(ctx);
CGContextBeginPath(ctx);
... draw path
CGContextClosePath(ctx);

CGContextClip(ctx);
CGContextSaveGState(ctx);
[self.image drawAtPoint:CGPointZero];
CGContextDrawPath(ctx, kCGPathFillStroke);  // Paint the context
CGContextRestoreGState(ctx);
UIGraphicsPopContext();

我有多个带有这个 CALayer 的 UIViews。当发生特定事件时,我需要获取 CALayer 上下文绘图并将其应用于另一个 UIView 中的另一个 CALayer,同时保留当前上下文绘图。我尝试UImage从上下文中缓存,然后重新应用它,但无济于事。

self.cachedImage = UIGraphicsGetImageFromCurrentImageContext();

我试过这个重新应用它:

self.contents = (id)self.cachedImage.CGImage;

或者

[self.cachedImage drawAtPoint:CGPointZero];

我对此很陌生,需要一些关于如何保存或添加到这些 CALayers 的上下文图中的指导

编辑

我也在 aUIView而不是 a上尝试过这个CALayer。这就是我所拥有的:

-(void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.cachedImage.image drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0];
    CGContextBeginPath(ctx);
    ... draw path ...
    CGContextClosePath(ctx);
    CGContextClip(ctx);
    [self.image drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0];
    CGContextDrawPath(ctx, kCGPathFillStroke);

    UIGraphicsBeginImageContext(self.bounds.size);
    self.cachedImage.image = UIGraphicsGetImageFromCurrentImageContext();
    [self.cachedImage setAlpha:1.0];
    UIGraphicsEndImageContext();
}

这仍然清除了过去的上下文绘图。如果我 NSLogself.cachedImage.image它肯定存在。

我的一部分想知道它是否与此有关:CGContextClip()

4

1 回答 1

1

你真的不应该在 中设置任何东西-drawRect:,而只是绘图。您尝试做的事情可能应该在其他地方完成。据我了解,您正试图将两个视图的绘图“合并”为一张图像?如果是这样,请创建图像上下文,绘制并单独保存这些图像,在您的-drawRect:Like Tommy状态之外,您应该只绘制视图的状态,而不更改对象的任何内容。

看看UIGraphicsBeginImageContext一个好的起点(ps 这也可以在后台线程上运行!)。

于 2013-08-26T19:20:59.563 回答