java创建图,用Java创建图像

Hello) Help solve the problem:

We need to create a green square image and display it.

I could draw a square, but I need to create it using java.

Please help me to do this)

That's what I tried to do:

import java.awt.Canvas;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class Game extends Canvas {

private static final long serialVersionUID = 1L;

private static final int WIDTH = 400;

private static final int HEIGHT = 400;

@Override

public void paint(Graphics g) {

super.paint(g);

int w = 10;

int h = 10;

int type = BufferedImage.TYPE_INT_ARGB;

BufferedImage image = new BufferedImage(w, h, type);

int color = 257; // RGBA value, each component in a byte

for (int x = 1; x < w; x++) {

for (int y = 1; y < h; y++) {

image.setRGB(x, y, color);

g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

}

}

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setSize(WIDTH, HEIGHT);

frame.add(new Game());

frame.setVisible(true);

}

}

But nothing is displayed (

Let me remind the goal - to create a picture in the form of green squares, help to make it)

解决方案

The simplest approach would be to simply use the graphics API...

@Override

public void paint(Graphics g) {

super.paint(g);

int w = 10;

int h = 10;

g.setColor(Color.GREEN);

g.fillRect(0, 0, width, height);

}

But something tells me this isn't what you want, but it does form the basics for what you need to achieve your result.

Start by making image a instance field...

private BufferedImage image;

Then you need to create the image...

int type = BufferedImage.TYPE_INT_ARGB;

image = new BufferedImage(w, h, type);

Graphics2D g2d = image.createGraphics();

g2d.setColor(Color.GREEN);

g2d.fillRect(0, 0, w, h);

g2d.dispoe();

Then in you paint method, you need to draw the image...

g.drawImage(image, x, y, this);

Take a look at the 2D Graphics trail for mor details

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值