您可以使用我的开源 GPUImage 框架中的 GPUImageSphereRefractionFilter 执行此操作:
我在this answer 中详细描述了它是如何工作的,以回答关于对 Android 的类似影响的问题。基本上,我使用片段着色器来折射穿过假想球体的光,然后使用它来查找包含源图像的纹理。使用简单的高斯模糊对背景进行模糊处理。
如果您想获得所显示图像的确切外观,您可能需要调整此片段着色器以向球体添加一些掠角颜色,但这应该会让您相当接近。
为了好玩,我决定尝试更接近地复制上面的玻璃球。我在球体上添加了掠射角光照和镜面光照反射,以及不反转折射纹理坐标,导致了这个结果:
我在这个较新的版本中使用了以下片段着色器:
varying highp vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform highp vec2 center;
uniform highp float radius;
uniform highp float aspectRatio;
uniform highp float refractiveIndex;
// uniform vec3 lightPosition;
const highp vec3 lightPosition = vec3(-0.5, 0.5, 1.0);
const highp vec3 ambientLightPosition = vec3(0.0, 0.0, 1.0);
void main()
{
highp vec2 textureCoordinateToUse = vec2(textureCoordinate.x, (textureCoordinate.y * aspectRatio + 0.5 - 0.5 * aspectRatio));
highp float distanceFromCenter = distance(center, textureCoordinateToUse);
lowp float checkForPresenceWithinSphere = step(distanceFromCenter, radius);
distanceFromCenter = distanceFromCenter / radius;
highp float normalizedDepth = radius * sqrt(1.0 - distanceFromCenter * distanceFromCenter);
highp vec3 sphereNormal = normalize(vec3(textureCoordinateToUse - center, normalizedDepth));
highp vec3 refractedVector = 2.0 * refract(vec3(0.0, 0.0, -1.0), sphereNormal, refractiveIndex);
refractedVector.xy = -refractedVector.xy;
highp vec3 finalSphereColor = texture2D(inputImageTexture, (refractedVector.xy + 1.0) * 0.5).rgb;
// Grazing angle lighting
highp float lightingIntensity = 2.5 * (1.0 - pow(clamp(dot(ambientLightPosition, sphereNormal), 0.0, 1.0), 0.25));
finalSphereColor += lightingIntensity;
// Specular lighting
lightingIntensity = clamp(dot(normalize(lightPosition), sphereNormal), 0.0, 1.0);
lightingIntensity = pow(lightingIntensity, 15.0);
finalSphereColor += vec3(0.8, 0.8, 0.8) * lightingIntensity;
gl_FragColor = vec4(finalSphereColor, 1.0) * checkForPresenceWithinSphere;
}
并且此滤镜可以使用 GPUImageGlassSphereFilter 运行。