1

我在 Android API Level 9 上。我将相机预览加载到 SurfaceView 中。我正在尝试在此之上绘制一个晕影面具。为此,我使用了 GLSurfaceView。我使用以下片段着色器代码(或者它是像素着色器吗?)在 XCode 着色器构建器中准备了一个掩码,到目前为止编译成功:

uniform sampler2D tex;

void main()
{ 
float innerAlpha = 0.0;
float outerAlpha = 1.0;
float len = 1.7;
float startAdjustment = -0.2;
float diff = 0.4;
float alphaStep = outerAlpha / len;
vec2 center = vec2(0.5, 0.5);
vec2 foc1 = vec2(diff,0.);
vec2 foc2 = vec2(-diff,0.);
float r = distance(center+foc1,gl_TexCoord[0].xy) + distance(center+foc2,gl_TexCoord[0].xy);
float alpha = r  - (diff * 2.0) * alphaStep - startAdjustment;
vec4 vColor = vec4(0.,0.,0., innerAlpha + alpha);
gl_FragColor = vColor;
}

但是,我不知道如何在 Android 代码中实现这一点。基本上我认为我需要创建一个矩形,它将覆盖整个视图并在其上应用这种代码生成的纹理。我只是无法弄清楚实际的代码。理想情况下,它应该在 OpenGL ES 2.0 中。

编辑1:

@Tim - 我试着按照这里的教程http://developer.android.com/training/graphics/opengl/draw.html 和这里 http://www.learnopengles.com/android-lesson-one-getting-started / 我基本明白了,怎么画一个三角形。但我不明白,如何绘制矩形 - 我的意思是我真的需要实际绘制两个三角形还是我可以立即定义矩形(或其他复杂形状)?至于纹理 - 在我见过的所有教程中,纹理实际上是从图像文件中加载的,但我很想知道,我如何才能真正使用上面的像素着色器生成一个。

4

1 回答 1

0

Meanwhile, I have found the answer, how to draw the oval shaped mask.

Actually, the problem was, that I was thinking of gl_FragCoord in the range of 0.0 to 1.0, but they have to be specified in actual pixels instead, e.g. 600.0 x 900.0 etc.

With little tweaks (changing vec2's to floats) I have been able to draw nice oval shaped mask over the whole screen in OpenGL. Here is the final fragment shader. Note, that you must specify the uniforms before drawing. If you are gonna try this, make sure to keep uSlope to somewhere between 0.1 and 2.0 to get meaningful results. Also, please, note that uInnerAlpha has to be lower than uOuterAlpha with this particular piece of code. For a typical vignette, uInnerAlpha is 0.0 and uOuterAlpha is 1.0.

precision mediump float;

uniform float uWidth;
uniform float uHeight;
uniform float uSlope;
uniform float uStartAdjustment;
uniform float uEllipseLength;
uniform float uInnerAlpha;
uniform float uOuterAlpha;

void main() {

float gradientLength = uHeight * uSlope;
float alphaStep = uOuterAlpha / gradientLength;
float x1 = (uWidth / 2.0);
float y1 = (uHeight / 2.0) - uEllipseLength;
float x2 = (uWidth / 2.0);
float y2 = (uHeight / 2.0) + uEllipseLength;

float dist1 = sqrt(pow(abs(gl_FragCoord.x - x1), 2.0) + pow(abs(gl_FragCoord.y - y1), 2.0));
float dist2 = sqrt(pow(abs(gl_FragCoord.x - x2), 2.0) + pow(abs(gl_FragCoord.y - y2), 2.0));
float dist = (dist1 + dist2);

float alpha = ((dist - (uEllipseLength * 2.0)) * alphaStep - uStartAdjustment) + uInnerAlpha;
if (alpha > uOuterAlpha) {
    alpha = uOuterAlpha;
}
if (alpha < uInnerAlpha) {
    alpha = uInnerAlpha;
}

vec4 newColor = vec4(1.0, 1.0, 1.0, alpha);

gl_FragColor = newColor;

}
于 2012-09-26T10:53:20.210 回答