Java Graphics - Count number of pixels used in drawLine function
I have given here Java Graphics program to count the number of pixels used to draw a Line by drawLine function
Source Code
import java.lang.*; import java.util.*; import java.util.List; import java.io.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.Image.*; import javax.swing.JFrame; import javax.swing.JPanel; public class CountPixels_Line extends JPanel { static public int pixelDrawnCount = 0; static public int width = 300; static public int height = 300; public java.awt.image.BufferedImage myshape = new java.awt.image.BufferedImage(width,height, java.awt.image.BufferedImage.TYPE_INT_RGB); public int CountPixelsInLine(int x1, int y1, int x2, int y2) { Graphics2D gtemp = myshape.createGraphics(); gtemp.setPaint(Color.white); gtemp.fillRect(0,0,width,width); gtemp.setPaint(Color.red); gtemp.drawLine(x1,y1,x2,y2); int pixelcount = 0; for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { int color = myshape.getRGB(i,j); int red = (color & 0x00ff0000) >> 16; int green = (color & 0x0000ff00) >> 8; int blue = color & 0x000000ff; if(red == 255 && green == 0 && blue == 0) { pixelcount++; } } } gtemp.dispose(); return pixelcount; } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.drawImage(myshape, null, null); String buffer = "Number of pixels drawn: " + pixelDrawnCount; g2.drawString(buffer, 10, height - 50); } public static void main(String args[]) { CountPixels_Line panel = new CountPixels_Line(); //pixelDrawnCount = panel.CountPixelsInLine(5,10,30,30); pixelDrawnCount = panel.CountPixelsInLine(80,20,10,80); JFrame frame = new JFrame("Count Pixels Demo"); frame.add(panel); frame.pack(); frame.setSize(width,width); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Output
|