gpt4 book ai didi

java - 将图像添加到形状

转载 作者:行者123 更新时间:2023-12-01 11:21:44 26 4
gpt4 key购买 nike

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

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

最佳答案

首先查看 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();

关于java - 将图像添加到形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com