OpenGL提供了 void glScissor(GLint x, GLint y, GLsizei width, GLsizei height );
函数来实现裁剪功能。
在Libgdx中,同样提供了对应的接口:ScissorStack提供的函数: pushScissor函数
/** Pushes a new scissor {@link Rectangle} onto the stack, merging it with the current top of the stack. The minimal area of
* overlap between the top of stack rectangle and the provided rectangle is pushed onto the stack. This will invoke
* {@link GLCommon#glScissor(int, int, int, int)} with the final top of stack rectangle. In case no scissor is yet on the stack
* this will also enable {@link GL10#GL_SCISSOR_TEST} automatically.
* @return true if the scissors were pushed. false if the scissor area was zero, in this case the scissors were not pushed and
* no drawing should occur. */
public static boolean pushScissors (Rectangle scissor) {
fix(scissor);
if (scissors.size == 0) {
if (scissor.width < 1 || scissor.height < 1) return false;
Gdx.gl.glEnable(GL10.GL_SCISSOR_TEST);
} else {
// merge scissors
Rectangle parent = scissors.get(scissors.size - 1);
float minX = Math.max(parent.x, scissor.x);
float maxX = Math.min(parent.x + parent.width, scissor.x + scissor.width);
if (maxX - minX < 1) return false;
float minY = Math.max(parent.y, scissor.y);
float maxY = Math.min(parent.y + parent.height, scissor.y + scissor.height);
if (maxY - minY < 1) return false;
scissor.x = minX;
scissor.y = minY;
scissor.width = maxX - minX;
scissor.height = Math.max(1, maxY - minY);
}
scissors.add(scissor);
Gdx.gl.glScissor((int)scissor.x, (int)scissor.y, (int)scissor.width, (int)scissor.height);
return true;
}
popScissors函数:
/** Pops the current scissor rectangle from the stack and sets the new scissor area to the new top of stack rectangle. In case
* no more rectangles are on the stack, {@link GL10#GL_SCISSOR_TEST} is disabled. */
public static Rectangle popScissors () {
Rectangle old = scissors.pop();
if (scissors.size == 0)
Gdx.gl.glDisable(GL10.GL_SCISSOR_TEST);
else {
Rectangle scissor = scissors.peek();
Gdx.gl.glScissor((int)scissor.x, (int)scissor.y, (int)scissor.width, (int)scissor.height);
}
return old;
}
通过重写Actor的draw方法就可以实现裁剪功能,例如:
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
if(ScissorStack.pushScissors(mScissor)) {
super.draw(batch, parentAlpha);
ScissorStack.popScissors();
}
}
此功能可用来只画我们需要的区域来提高性能或是遮罩功能。