JOGL 2D形状
在上一节中,我们已经学习了如何在 JOGL 中绘制基本线条。使用相同的方法,我们还可以绘制各种类型的形状,例如正方形、矩形、三角形等。
JOGL 正方形示例
在这个例子中,我们将绘制四个不同的边,使它们都连接在一个正方形的点上。
package com.yiidian;
import javax.media.opengl.*;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.*;
public class Square implements GLEventListener {
@Override
public void init(GLAutoDrawable arg0) {
}
@Override
public void display(GLAutoDrawable drawable) {
final GL2 gl = drawable.getGL().getGL2();
//Drawing top edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(-0.4, 0.4);
gl.glVertex2d(0.4, 0.4);
gl.glEnd();
//Drawing bottom edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(-0.4, -0.4);
gl.glVertex2d(0.4, -0.4);
gl.glEnd();
//Drawing right edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(-0.4, 0.4);
gl.glVertex2d(-0.4, -0.4);
gl.glEnd();
//Drawing left edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(0.4, 0.4);
gl.glVertex2d(0.4, -0.4);
gl.glEnd();
}
@Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {
}
@Override
public void dispose(GLAutoDrawable arg0) {
}
public static void main(String[] args) {
final GLProfile gp = GLProfile.get(GLProfile.GL2);
GLCapabilities cap = new GLCapabilities(gp);
final GLCanvas gc = new GLCanvas(cap);
Square sq = new Square();
gc.addGLEventListener(sq);
gc.setSize(400, 400);
final JFrame frame = new JFrame("yiidian.com:JOGL Line");
frame.add(gc);
frame.setSize(500, 400);
frame.setVisible(true);
}
}
输出结果如下:
JOGL 三角形示例
在这个例子中,我们将绘制三个不同的边,它们都连接在一个三角形形状的点上。
package com.yiidian;
import javax.media.opengl.*;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.*;
public class Triangle implements GLEventListener {
@Override
public void init(GLAutoDrawable arg0) {
}
@Override
public void display(GLAutoDrawable drawable) {
final GL2 gl = drawable.getGL().getGL2();
// Base edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(-0.65, -0.65);
gl.glVertex2d(0.65, -0.65);
gl.glEnd();
//Right edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(0, 0.65);
gl.glVertex2d(-0.65, -0.65);
gl.glEnd();
//Left edge
gl.glBegin(GL2.GL_LINES);
gl.glVertex2d(0, 0.65);
gl.glVertex2d(0.65, -0.65);
gl.glEnd();
gl.glFlush();
}
@Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3, int arg4) {
}
@Override
public void dispose(GLAutoDrawable arg0) {
}
public static void main(String[] args) {
final GLProfile gp = GLProfile.get(GLProfile.GL2);
GLCapabilities cap = new GLCapabilities(gp);
final GLCanvas gc = new GLCanvas(cap);
Triangle tr = new Triangle();
gc.addGLEventListener(tr);
gc.setSize(400, 400);
final JFrame frame = new JFrame("yiidian.com:JOGL Triangle");
frame.add(gc);
frame.setSize(500, 400);
frame.setVisible(true);
}
}
输出结果如下:
因此,任何类型的图形都可以通过连接特定形状的线条来设计。
热门文章
优秀文章