在OpenGL ES 2.0中为iOS应用程序使用掩码

在OpenGL ES 2.0中为iOS应用程序使用掩码,ios,opengl-es,Ios,Opengl Es,我有一个应用程序,我希望用户在屏幕的某个特定区域绘制。为此,我使用了一张在可绘制区域为黑色,在不可绘制区域为透明的遮罩图片。因此,用户只能在遮罩内的屏幕区域和遮罩的黑色区域内绘制 我尝试通过模具缓冲区实现它,并修改了GLPaint示例项目中的一些代码: 然而,我仍然不知道模具缓冲区的用法。有人能帮我提供模具缓冲区的代码示例吗?另外,没有模具缓冲区有什么方法可以实现这一点吗?因为您的遮罩是纹理,模具缓冲区不是一个好主意 在遮罩渲染期间,必须对片段着色器中的透明像素使用“放弃;” 欢迎来到抗锯齿问

我有一个应用程序,我希望用户在屏幕的某个特定区域绘制。为此,我使用了一张在可绘制区域为黑色,在不可绘制区域为透明的遮罩图片。因此,用户只能在遮罩内的屏幕区域和遮罩的黑色区域内绘制

我尝试通过模具缓冲区实现它,并修改了GLPaint示例项目中的一些代码:


然而,我仍然不知道模具缓冲区的用法。有人能帮我提供模具缓冲区的代码示例吗?另外,没有模具缓冲区有什么方法可以实现这一点吗?

因为您的遮罩是纹理,模具缓冲区不是一个好主意

  • 在遮罩渲染期间,必须对片段着色器中的透明像素使用“放弃;”
  • 欢迎来到抗锯齿问题
出于好奇,这里有一些代码用于配置带有模具缓冲区的遮罩:

const bool invert_mask = false; // allow to draw inside or outside mask
unsigned mask_id = 1; // you can use this code multiple time without clearing stencil, just increment mask_id

glEnable(GL_STENCIL_TEST);
// write on stencil_mask
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glStencilFunc(GL_ALWAYS, mask_id, 0);

// remove depth test and color writing
glDepthMask(GL_FALSE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);


// TODO: draw geometry of mask here. (if you use a texture, dont forget to use discard in the shader 


// enabled depth & color writing
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_TRUE);

// no stencil write
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// test stencil value
glStencilFunc(invert_mask ? GL_NOTEQUAL : GL_EQUAL, mask_id, 0xff);


// TODO: draw  "clipped" geometry here


// finally, remove stencil test
glDisable(GL_STENCIL_TEST);
最简单的方法是根本不使用模具。创建一个灰度屏幕大小的纹理,将你的遮罩写在里面。然后将其绑定到片段着色器中:

uniform LOW_P sampler2D u_diffuse_sampler;
uniform LOW_P sampler2D u_mask_sampler;
varying mediump vec2 v_texcoord;

void main(void) {
    gl_FragColor = texture2D(u_diffuse_sampler, v_texcoord) * texture2D(u_mask_sampler, v_texcoord).r;
}