Java examples for 2D Graphics:Line
Draws a line using the z-buffer algorithm
//package com.java2s; import java.awt.*; public class Main { /**// w w w . ja va 2 s. com * Draws a line using the z-buffer algorithm * @param gr graphic object * @param x1 x coordinate of the first vertex * @param y1 y coordinate of the first vertex * @param z1 z coordinate of the first vertex * @param x2 x coordinate of the second vertex * @param y2 y coordinate of the second vertex * @param z2 z coordinate of the second vertex * @param zbuffer z depth buffer */ public static void drawLine(Graphics gr, int x1, int y1, int z1, int x2, int y2, int z2, int[][] zbuffer) { int dimX = zbuffer.length; int dimY = zbuffer[0].length; int difX, difY, difZ; int px, pz, py; if (y1 > y2) { y1 ^= y2; y2 ^= y1; y1 ^= y2; x1 ^= x2; x2 ^= x1; x1 ^= x2; z1 ^= z2; z2 ^= z1; z1 ^= z2; } if (x1 > 0 && x1 < dimX && y1 > 0 && y1 < dimY && zbuffer[x1][y1] >= z1) { zbuffer[x1][y1] = z1; gr.fillRect(x1, y1, 1, 1); } difX = x2 - x1; difY = y2 - y1; difZ = z2 - z1; int compDifX; if (x2 > x1) compDifX = x2 - x1; else compDifX = x1 - x2; if ((compDifX < y2 - y1)) { for (py = y1 + 1; py < y2; py++) { px = x1 + ((py - y1) * difX / difY); pz = z1 + ((py - y1) * difZ / difY); if (px > 0 && px < dimX && py > 0 && py < dimY && zbuffer[px][py] >= pz) { zbuffer[px][py] = pz; gr.fillRect(px, py, 1, 1); } } } else if (x1 > x2) { for (px = x2 + 1; px < x1; px++) { py = y1 + ((px - x1) * difY / difX); pz = z1 + ((px - x1) * difZ / difX); if (px > 0 && px < dimX && py > 0 && py < dimY && zbuffer[px][py] >= pz) { zbuffer[px][py] = pz; gr.fillRect(px, py, 1, 1); } } } else { for (px = x1 + 1; px < x2; px++) { py = y1 + ((px - x1) * difY / difX); pz = z1 + ((px - x1) * difZ / difX); if (px > 0 && px < dimX && py > 0 && py < dimY && zbuffer[px][py] >= pz) { zbuffer[px][py] = pz; gr.fillRect(px, py, 1, 1); } } } if (x2 > 0 && x2 < dimX && y2 > 0 && y2 < dimY && zbuffer[x2][y2] >= z2) { zbuffer[x2][y2] = z2; gr.fillRect(x2, y2, 1, 1); } } }