问题描述
我正在将内容绘制到视频帧上,我发现的最好方法是从视频帧中获取 CVImageBufferRef
,然后像使用任何其他 CGContext 绘制一样在其中进行绘制.
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.
现在我有大量的 UIViews,我只是简单地创建了它们,而没有将它们添加到任何超级视图中.我希望在没有 renderInContext 的情况下绘制这些 UIViews,因为这将花费我每帧 1 秒或每秒 30 秒的视频渲染时间.
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.
如果我使用 drawViewHierarchyInRect
什么都不会绘制.
If i use drawViewHierarchyInRect
nothing is drawn.
如果我使用 drawRect
什么也没有绘制,我会得到很多无效的上下文错误
If i use drawRect
nothing is drawn and i get lots of invalid context errors
我之前调用了 setNeedsDisplay
和 setNeedsLayout
并且 Rects 都是有效的.
I am calling setNeedsDisplay
and setNeedsLayout
before and the Rects are all valid.
与 UILabel 等非自定义 UIView 存在同样的问题.
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);
推荐答案
如果 UIViews 没有添加到任何超视图中,就无处可画.从根本上说,绘图只发生在设备屏幕上(除了专门针对专门创建的上下文(如 pdf 或图像上下文)或位图上下文(如您创建的上下文)进行渲染).
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).
当您通常绘制到 UIView 时,它是层次结构的一部分,最终是将所有绘图映射到设备屏幕的单个图形上下文的一部分.
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.
您可以在使用 CG 调用创建的位图上下文中进行绘制.如果您尝试绘制文本,您可能需要使用 CoreText.
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.
这篇关于当 UIView 未附加到任何层次结构时,如何将 UIView 绘制到没有 renderInContext 的 CGContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!