CALayer setNeedsDisplayInRect - InRect 的意义是什么?或者在drawInContext中更快地绘制
我有一个 CALayer (imageLayer),以及一个充当 CALayer (maskLayer) 上的掩模的子类 CALayer。
我用手指在 maskLayer 上绘画,以便可以暂时擦除 imageLayer 的一部分。
我通过保留一个位图上下文 (maskContext) 并在 TouchMoved 中向其添加笔划来实现此目的。所以我的 maskContext 只保存我画的所有笔画。在touchesMoved中,我执行[maskLayer setNeedsDisplay]
;
在我的子类 maskLayer 中,我有 drawInContext
方法:
-(void)drawInContext:(CGContextRef)ctx
{
CGImageRef image = CGBitmapContextCreateImage(maskContext);
CGContextDrawImage(ctx, CGRectMake(0,0,self.frame.size.width, self.frame.size.height), image);
}
这一切都运行得很好,但速度非常慢,因为它为每个 TouchMoved 事件绘制整个视图。
我想过使用 [maskLayer setNeedsDisplayInRect:rect]
但我想知道重点是什么,因为 drawInContext
不查看矩形。我可以将矩形传递给 drawInContext
,但我只需使用 setNeedsDisplay
即可做到这一点。
对于 CALayer 来说,是否有 setNeedsDisplayInRect
能做而 setNeedsDisplay
不能做的事情?
(我知道如果我使用 drawRect
,它将接受定义的矩形,但 CALayer 的 drawInContext
不会)
另外,有没有更好的方法来完成这个用手指绘画遮盖?主要问题是 CGContext 不是画布,不记得以前的笔划,因此必须始终重绘它们。
I have a CALayer (imageLayer), and a subclassed CALayer that acts as a mask on the CALayer (maskLayer).
I am painting with a finger onto the maskLayer so that I can temporarily erase out part of the imageLayer.
I am accomplishing this by keeping one Bitmap Context (maskContext), and adding a stroke to it in touchesMoved. So my maskContext just holds all the strokes I have painted. In touchesMoved, I do [maskLayer setNeedsDisplay]
;
in my subclassed maskLayer, I have the drawInContext
method:
-(void)drawInContext:(CGContextRef)ctx
{
CGImageRef image = CGBitmapContextCreateImage(maskContext);
CGContextDrawImage(ctx, CGRectMake(0,0,self.frame.size.width, self.frame.size.height), image);
}
This all works out really well, but is very slow as it's drawing the whole view for each touchesMoved event.
I thought of using [maskLayer setNeedsDisplayInRect:rect]
but I wondered what the point is, as drawInContext
does not look at the rect. I could pass the rect to drawInContext
, but I could do that with just setNeedsDisplay
.
Is there something that setNeedsDisplayInRect
does that setNeedsDisplay
doesn't for a CALayer?
(I am aware that if I were using drawRect
, that would accept the defined rect, but a CALayer's drawInContext
doesn't)
Also, is there any better way of accomplishing this masking by painting with a finger? The main problem is that the CGContext is not a canvas and does not remember previous strokes, so they have to be redrawn all the time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果通过调用
setNeedsDisplayInRect:
来标记要显示的图层,则可以使用CGContextGetClipBoundingBox
来获取标记为在drawInContext:
中显示的区域。If you mark a layer to display by calling
setNeedsDisplayInRect:
then you can useCGContextGetClipBoundingBox
to get the area marked to display in yourdrawInContext:
.