将 UIView 的内容渲染为 OpenGL 纹理 [英] Render contents of UIView as an OpenGL texture
问题描述
有没有办法在 iOS 中使用 OpenGL 将 UIView 的内容渲染为纹理?还是CGLayer的内容?
Is there a way to render the contents of a UIView as a texture with OpenGL in iOS? Or the contents of a CGLayer?
推荐答案
您可以使用视图的 layer 属性来获取 CALayer 并使用 renderInContext: 在其上绘制到 CoreGraphics 上下文中.您可以使用自己分配的内存设置 CoreGraphics 上下文,以便接收像素缓冲区.然后,您可以通过正常方法将其上传到 OpenGL.
You can use the view's layer property to get the CALayer and use renderInContext: on that to draw into a CoreGraphics context. You can set up a CoreGraphics context with memory you allocate yourself in order to receive a pixel buffer. You can then upload that to OpenGL by the normal method.
所以:有一种方法可以获取 UIView 的像素内容,而 OpenGL 将接受像素缓冲区.两者之间没有具体的联系.
So: there's a means to get the pixel contents of a UIView and OpenGL will accept pixel buffers. There's no specific link between the two.
即兴编码,过程类似于:
Coding extemporaneously, the process would be something like:
UIView *view = ... something ...;
// make space for an RGBA image of the view
GLubyte *pixelBuffer = (GLubyte *)malloc(
4 *
view.bounds.size.width *
view.bounds.size.height);
// create a suitable CoreGraphics context
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context =
CGBitmapContextCreate(pixelBuffer,
view.bounds.size.width, view.bounds.size.height,
8, 4*view.bounds.size.width,
colourSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colourSpace);
// draw the view to the buffer
[view.layer renderInContext:context];
// upload to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0,
GL_RGBA,
view.bounds.size.width, view.bounds.size.height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, pixelBuffer);
// clean up
CGContextRelease(context);
free(pixelBuffer);
这不会处理在没有非 2 次幂纹理扩展的硬件上的非 2 次幂大小视图的问题,并假设已经生成并绑定了合适的 GL 纹理名称.自己检查一下,但我认为 SGX 硬件(即 iPhone 3GS 及以上、iPad 以及除 8GB 第三代 iPod Touch 及以上)支持非 2 的幂,但 MBX 不支持.
That doesn't deal with issues surrounding non-power-of-two sized views on hardware without the non-power-of-two texture extension and assumes a suitable GL texture name has already been generated and bound. Check for yourself, but I think non-power-of-two is supported on SGX hardware (ie, iPhone 3GS onwards, the iPad and all but the 8gb third generation iPod Touch onwards) but not on MBX.
此处处理非 2 次幂纹理的最简单方法可能是创建足够大的 2 次幂纹理,并使用 glTexSubImage2D 仅上传源 UIView 中的部分.
The easiest way to deal with non-power-of-two textures here is probably to create a large enough power of two texture and to use glTexSubImage2D to upload just the portion from your source UIView.
这篇关于将 UIView 的内容渲染为 OpenGL 纹理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!