用Java 建立像素網格
對於有抱負的像素編輯器來說,設計一個允許精確顏色操作的網格系統可能是令人畏懼的。然而,Java 提供了一些有用的元件來簡化這個過程。
JButton 作為網格單元
最初,使用 JButton 作為網格單元可能看起來效率低。雖然它允許修改單一儲存格,但在處理大量儲存格時會變得很麻煩。
替代網格實作
更有效的解決方案是利用drawImage()方法和縮放滑鼠座標。此技術創建更大的“像素”,同時保留類似網格的行為。
示例代碼
以下代碼演示了此方法:
<code class="java">import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; public class Grid extends JPanel implements MouseMotionListener { private BufferedImage img; private int imgW, imgH, paneW, paneH; public Grid(String name) { super(true); // Load an image icon Icon icon = UIManager.getIcon(name); imgW = icon.getIconWidth(); imgH = icon.getIconHeight(); // Calculate panel dimensions this.setPreferredSize(new Dimension(imgW * 10, imgH * 10)); // Create an image buffer img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB); // Draw the icon to the buffer Graphics2D g2d = (Graphics2D) img.getGraphics(); icon.paintIcon(null, g2d, 0, 0); g2d.dispose(); // Register mouse motion listener this.addMouseMotionListener(this); } @Override protected void paintComponent(Graphics g) { paneW = this.getWidth(); paneH = this.getHeight(); // Draw the buffered image g.drawImage(img, 0, 0, paneW, paneH, null); } @Override public void mouseMoved(MouseEvent e) { // Scale mouse coordinates based on panel dimensions Point p = e.getPoint(); int x = p.x * imgW / paneW; int y = p.y * imgH / paneH; // Retrieve and display color information at the grid location int c = img.getRGB(x, y); this.setToolTipText(x + "," + y + ": " + String.format("%08X", c)); } @Override public void mouseDragged(MouseEvent e) { } public static void main(String[] args) { // Create a JFrame and add the Grid panel JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new Grid("Tree.closedIcon")); f.pack(); f.setVisible(true); } }</code>
用法
結果
將顯示網格,允許使用者將滑鼠移到像素化影像上,同時獲取顏色資訊每個細胞。
以上是如何在 Java 中建立像素化網格以進行精確的顏色操作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!