将图像添加到形状

时间:2015-07-01 00:09:34

标签: java eclipse

所以我正在学习在eclipse上创建一个java游戏。我学会了添加形状等。我还学会了如何绘制形状(改变颜色)我想知道如何将图像添加到形状中。这是绘制矩形的代码。

public void paintColumn(Graphics g, Rectangle column)
    {
        g.setColor(Color.blue.darker());
        g.fillRect(column.x, column.y, column.width, column.height);
    }

2 个答案:

答案 0 :(得分:1)

首先查看Reading/Loading an Image以了解有关如何加载图片的详细信息,另外,请查看2D Graphics以获取有关2D图形API的更多详细信息。

基本上,你加载图像,绘制它然后在它周围绘制形状。

Rectangle

    Graphics2D g2d = (Graphics2D) g.create();
    int x = (getWidth() - img.getWidth()) / 2;
    int y = (getHeight() - img.getHeight()) / 2;
    g2d.drawImage(img, x, y, this);
    g2d.setColor(Color.RED);
    g2d.drawRect(x, y, img.getWidth(), img.getHeight());
    g2d.dispose();

现在,这只是在图像上绘制矩形,如果你想,以某种方式“框架”图像,你可以填充矩形,使其大于图像,但你必须先填充,然后绘制图像

FilledRectangle

    Graphics2D g2d = (Graphics2D) g.create();
    int x = (getWidth() - img.getWidth()) / 2;
    int y = (getHeight() - img.getHeight()) / 2;
    g2d.setColor(Color.RED);
    g2d.fillRect(x - 10, y - 10, img.getWidth() + 20, img.getHeight() + 20);
    g2d.drawImage(img, x, y, this);
    g2d.dispose();

答案 1 :(得分:0)

只需创建一个BufferedImage对象:

BufferedImage image = ImageIO.read(filename);

然后代替做g.drawShape做:

g.drawImage(image, [starting x], [starting y], [image width], [image height], [image observer]);

在您的情况下,您可能不需要图像观察者,因此您可以将null放在该位置。

那么最简单的方法就是在图像上方绘制矩形。即使图像实际上不在矩形的“内部”,分层效果也会使其看起来像是一样。您可以使用drawRect代替fillRect,这样您就可以在图片周围找到边框。

为确保您的矩形最终位于图像顶部,并且由于图像大小相同而未被覆盖,请确保将drawRect行放在 drawImage之后。

g.drawRect([starting x], [starting y], [width], [height]);

有关绘制图像的更多信息,请查看这些Graphics Java Docs