将图像添加到形状 [英] Adding an image to a shape

查看:68
本文介绍了将图像添加到形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So i'm learning to create a java game on eclipse. I learned adding shapes and such. I also learned how to paint the shapes (change the colours) I was wondering how to add an image to the shape. This is the code for painting the rectangle.

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

推荐答案

首先查看读取/加载图像以获取有关如何加载图像的详细信息,另请参阅

Start by having a look at Reading/Loading an Image for details about how to load a image, also, have a look at 2D Graphics for more details about 2D Graphics API.

基本上,您加载图像,先绘制图像,然后在其周围绘制形状.

Basically, you load the image, you draw it and then draw the shape around it.

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

现在,这只是在图像上绘制矩形,如果您希望以某种方式构图"图像,则可以填充矩形,使其比图像大,但必须先填充,然后再填充绘制图像

Now, this just draws the rectangle over the image, if you want to, somehow "frame" the image instead, you could fill the rectangle, making it larger then the image, but you'd have to fill first, then draw the image

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

这篇关于将图像添加到形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆