如何给像素上色?

2022-09-03 03:18:29

我必须创建一个简单的2D动画,而无需使用各种基元来绘制线条,圆形等。它必须通过操纵像素并通过着色像素来实现绘制线条,圆形等的算法之一来完成。

我想过使用Turbo C来实现这个目的,但我使用ubuntu。所以我尝试使用dosbox来安装和运行turbo C,但无济于事。

现在我唯一的选择是Java。是否可以在Java中操作像素?我找不到任何好的教程。如果可以给出相同的示例代码,那就太好了。


答案 1

java.awt.BufferedImage有一个设置单个像素颜色的方法。此外,您可能还想看看 java.awt.Color,尤其是它的方法,它可以将 Colors 转换为整数,您可以将其放入 的参数中。setRGB(int x, int y, int rgb)getRGB()int rgbsetRGB


答案 2
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DirectDrawDemo extends JPanel {

    private BufferedImage canvas;

    public DirectDrawDemo(int width, int height) {
        canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        fillCanvas(Color.BLUE);
        drawRect(Color.RED, 0, 0, width/2, height/2);
    }

    public Dimension getPreferredSize() {
        return new Dimension(canvas.getWidth(), canvas.getHeight());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(canvas, null, null);
    }


    public void fillCanvas(Color c) {
        int color = c.getRGB();
        for (int x = 0; x < canvas.getWidth(); x++) {
            for (int y = 0; y < canvas.getHeight(); y++) {
                canvas.setRGB(x, y, color);
            }
        }
        repaint();
    }


    public void drawLine(Color c, int x1, int y1, int x2, int y2) {
        // Implement line drawing
        repaint();
    }

    public void drawRect(Color c, int x1, int y1, int width, int height) {
        int color = c.getRGB();
        // Implement rectangle drawing
        for (int x = x1; x < x1 + width; x++) {
            for (int y = y1; y < y1 + height; y++) {
                canvas.setRGB(x, y, color);
            }
        }
        repaint();
    }

    public void drawOval(Color c, int x1, int y1, int width, int height) {
        // Implement oval drawing
        repaint();
    }



    public static void main(String[] args) {
        int width = 640;
        int height = 480;
        JFrame frame = new JFrame("Direct draw demo");

        DirectDrawDemo panel = new DirectDrawDemo(width, height);

        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


}

替代文本 http://grab.by/grabs/39416148962d1da3de12bc0d95745341.png


推荐