简单的PixelGrid,我可以用鼠标绘制大像素(选择分辨率)



我在Java中寻找一种方法,使一个简单的网格填充像素,如果你拖动鼠标。所以只是一个简单的绘图面…

现在重要的是,我可以选择分辨率,或者换句话说,选择像素大小…

我需要在网格中作为神经网络输入模式的图纸。所以我想在2array中检索信息。

例如:一个20*20的网格,其中每个"像素"(或者更合适的是正方形)实际上是一个正方形,比如说10*10的真实像素。

如何制作一个简单的PixelGrid,我可以用鼠标绘制大像素(选择分辨率)?

  1. 创建boolean的2D数组(用于存储选定的区域或像素),所有数组元素默认为false。
  2. 添加MouseMotionListener到自定义绘画表面。
  3. 绘画表面可能是
    • 扩展的JPanel,或…
    • JLabel
  4. 显示
  5. BufferedImage
  6. mouseDragged(MouseEvent)方法中,决定转换为什么"像素",并将其设置为true
  7. 调用面板上的repaint(),或者更新图像并重新绘制标签。
  8. 绘制时,更改每个true数组元素对应区域的颜色。

感谢您的帮助!我以为有人可能已经做了一个像我想要的网格类,但不是等待,我接受了你的建议,并开始按照你的行编码自己。

如果您只是想执行并查看代码。我仍然有一个小问题与dragMouse-action,它总是填满方块正上方的我想要的。为什么会这样?如果我在代码中做了一些奇怪或不必要的事情,也请告诉我。再次感谢你。

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class GridBox extends JPanel implements MouseMotionListener {
    private static final long serialVersionUID = 1L;
    //The Array with the Rectangles
    private static List<List<DrawnRectangle>> pixels = new ArrayList<List<DrawnRectangle>>();
    //The Frame (JComponent)
    private static JFrame f = null;
    public GridBox()
    {
        this.addMouseMotionListener(this);
    }
    public static void main(String[] args)
    {
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setPreferredSize(new Dimension(400, 400));
        f.add(new GridBox());
        f.pack();
        f.setVisible(true);
    }
    @Override
    protected void paintComponent(Graphics g)
    {
        drawGrid((Graphics2D)g, 20, 20, 400, 400);
    }
    public static void drawGrid(Graphics g, int rowAmount, int columnAmount, int width, int height)
    {
        int pixelSizeW = width / columnAmount;
        int pixelSizeH = height / rowAmount;
        DrawnRectangle.defaultThickness = 1;
        for(int row = 0; row < rowAmount; row++)
        {
            List<DrawnRectangle> currentRow = new ArrayList<DrawnRectangle>();
            for(int column = 0; column < columnAmount; column++)
            {
                DrawnRectangle current = new DrawnRectangle( f, (row*pixelSizeW), (column*pixelSizeH), pixelSizeW, pixelSizeH);
                currentRow.add(current);
                current.paint();
            }
            pixels.add(currentRow);
        }
    }
    public void clearGrid()
    {
        for( List<DrawnRectangle> ListRect : pixels)
        {
            for( DrawnRectangle rect : ListRect)
            {
                rect.clearInterior();
            }
        }
    }
    @Override
    public void mouseDragged(MouseEvent e)
    {
        Point p = e.getPoint();
        for( List<DrawnRectangle> ListRect : pixels)
        {
            for( DrawnRectangle rect : ListRect)
            {
                if( rect.contains(p))
                {
                    rect.fill(Color.black);
                }
            }
        }
    }
    @Override
    public void mouseMoved(MouseEvent arg0)
    {
    }
}

最新更新