How do i draw a UIView to a CGContext without rend

2019-08-15 07:08发布

问题:

I am drawing stuff onto a video frame and the best way i found is to get the CVImageBufferRef from the Video frame and then draw into/onto it like with any other CGContext drawing.

Now i have loads of UIViews that i simply create without adding them to any superview. I want these UIViews drawn without renderInContext because this would take me 1 second per frame or 30 sec rendertime per second of video.

If i use drawViewHierarchyInRect nothing is drawn.

If i use drawRect nothing is drawn and i get lots of invalid context errors

I am calling setNeedsDisplayand setNeedsLayout before and the Rects are all valid.

Same issue with non-custom UIViews like a UILabel.

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

   // Lock the image buffer
    CVPixelBufferLockBaseAddress(imageBuffer,0);



    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(CVPixelBufferGetBaseAddress(imageBuffer),
                                                     CVPixelBufferGetWidth(imageBuffer),
                                                     CVPixelBufferGetHeight(imageBuffer),
                                                     8,
                                                     CVPixelBufferGetBytesPerRow(imageBuffer),
                                                     colorSpace,
                                                     kCGBitmapByteOrder32Little |
                                                     kCGImageAlphaPremultipliedFirst);


    // now i want to draw my UIView


    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);



    // Unlock the image buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

回答1:

If the UIViews are not added to any superviews, there is nowhere to draw to. Fundamentally, drawing only happens on the device screen (except for rendering specifically to specially created contexts like pdf or image contexts or a bitmap context like the one you created).

When you normally draw to a UIView, it is part of a hierarchy that ultimately is part of a single graphics context that maps all drawing to the devices screen.

You can draw into the bitmap context you created using CG calls. If you are trying to draw text you may need to use CoreText.