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

前端 未结 1 1691
南旧
南旧 2021-02-10 04:40

I have read what I believe to be the relevant parts of the Quartz 2D Programming Guide, but cannot find an answer to the following (they don\'t seem to talk a lot about iOS in t

相关标签:
1条回答
  • 2021-02-10 04:46

    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.

    0 讨论(0)
提交回复
热议问题