libgdx 裁剪多边形(clip polygon、masking polygon)
直接放例子代码,代码中以任意四边形为例,如果需要做任意多边形,注意libgdx不能直接用ShapeRender填充多边形,需要先切割成三角形。
public static void drawClip(Batch batch, Polygon polygon, TextureRegion region, float x, float y) { float[] vertices = polygon.getVertices(); if (shapes == null) { shapes = new ShapeRenderer(); } //2. clear our depth buffer with 1.0 Gdx.gl.glClearDepthf(1f); Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT); //3. set the function to LESS Gdx.gl.glDepthFunc(GL20.GL_LESS); //4. enable depth writing Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); //5. Enable depth writing, disable RGBA color writing Gdx.gl.glDepthMask(true); Gdx.gl.glColorMask(false, false, false, false); ///////////// Draw mask shape(s) //6. render your primitive shapes shapes.begin(ShapeRenderer.ShapeType.Filled); shapes.setColor(1f, 0f, 0f, 0.5f); shapes.identity(); shapes.triangle(vertices[0], vertices[1], vertices[4], vertices[5], vertices[2], vertices[3]); shapes.triangle(vertices[0], vertices[1], vertices[4], vertices[5], vertices[6], vertices[7]); // shapes.polyline(polygon.getVertices()); shapes.end(); ///////////// Draw sprite(s) to be masked if (!batch.isDrawing()) { batch.begin(); } //8. Enable RGBA color writing // (SpriteBatch.begin() will disable depth mask) Gdx.gl.glColorMask(true, true, true, true); //9. Make sure testing is enabled. Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); //10. Now depth discards pixels outside our masked shapes Gdx.gl.glDepthFunc(GL20.GL_EQUAL); //push to the batch batch.draw(region, x, y); //end/flush your batch batch.end(); Gdx.gl.glDisable(GL20.GL_DEPTH_TEST); }