如何为像素着色?

raz*_*r35 13 java graphics pixel

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

我考虑过使用Turbo C,但我使用的是ubuntu.所以我尝试使用dosbox来安装和运行turbo C,但无济于事.

现在我唯一的选择是Java.是否有可能在Java中操纵像素?我找不到任何相同的好教程.如果可以给出相同的示例代码,那将是很好的.

小智 29

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


I82*_*uch 23

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);
    }


}
Run Code Online (Sandbox Code Playgroud)

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