How to create a CGLayer from a UIView for off-screen drawing

本小妞迷上赌 提交于 2019-12-03 08:18:03

First of all, if you are doing it from in an iOS environment, I think you are right. The documentation clearly said that the only way to obtain a CGContextRef is by

CGContextRef ctx = UIGraphicGetCurrentContext();

Then you use that context for creating the CGLayer with

CGLayerRef layer = CGLayerCreateWithContext(ctx, (CGSize){0,0}, NULL);

And if you want to draw on that layer, you have to draw it with the context you get from the layer. (It is somewhat different from the context you passed in earlier to create the CGLayer). Im guessing the CGLayerCreateWithContext saves the information it can get from the context passed in, but not everything. (One of the example is the ColorSpace information, you have to re-specify when you fill something with the context from CGLayer).

You can get the CGLayer context reference from the CGLayerGetContext() function and use that to draw.

CGContextRef layerCtx = CGLayerGetContext(layer);
CGContextBeginPath(layerCtx);
CGContextMoveToPoint(layerCtx, -10, 10);
CGContextAddLineToPoint(layerCtx, 100, 10);
CGContextAddLineToPoint(layerCtx, 100, 100);
CGContextClosePath(layerCtx);

One point that I found out is when you draw something offscreen, it automatically clips the thing offscreen. (make sense, so it doesnt draw things that is not seen) but when you move the layer (using the matrix transformation). The clipped path is not showing (missing).

One last thing, if you save the reference to a layer into a variable and later on you want to draw it, you can use CGContextDrawLayerAtPoint() method like

CGContextDrawLayerAtPoint(ctx, (CGPoint) {newPointX, newPointY}, layer);

It will sort of "stampt" or "draw" the layer at that newPointX and new PointY coordinate.

I hope that answer your question, if its not please let me know.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!