简体   繁体   English

在Java Swing中用模式填充矩形

[英]Fill rectangle with pattern in Java Swing

I know how to fill a rectangle in Swing with a solid color: 我知道如何用纯色填充Swing中的矩形:

Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0,0,100,100);

I know how to fill it with an image: 我知道如何用图像填充它:

BufferedImage bi;
Graphics2D g2d = bi.createGraphics();
g2d.setPaint (new Color(r, g, b));
g2d.fillRect (0, 0, bi.getWidth(), bi.getHeight());

But how to fill rectangle of size 950x950 with some tiled pattern of size 100x100? 但是如何用一些尺寸为100x100的平铺图案填充尺寸为950x950的矩形?

(pattern image should be used 100 times) (图案图像应使用100次)

You're on the right track with setPaint . 您正在使用setPaint进入正确的轨道。 However, instead of setting it to a color, you want to set it to a TexturePaint object. 但是,您不想将其设置为颜色,而是将其设置为TexturePaint对象。

From the Java tutorial : Java教程

The pattern for a TexturePaint class is defined by a BufferedImage class. TexturePaint类的模式由BufferedImage类定义。 To create a TexturePaint object, you specify the image that contains the pattern and a rectangle that is used to replicate and anchor the pattern. 要创建TexturePaint对象,请指定包含图案的图像以及用于复制和锚定图案的矩形。 The following image represents this feature: 以下图像代表此功能: 示例图片

If you have a BufferedImage for the texture, create a TexturePaint like so: 如果您有纹理的BufferedImage ,请创建一个TexturePaint如下所示:

TexturePaint tp = new TexturePaint(myImage, new Rectangle(0, 0, 16, 16));

where the given rectangle represents the area of the source image you want to tile. 给定的矩形表示要平铺的源图像的区域。

The constructor JavaDoc is here . 构造函数JavaDoc就在这里

Then, run 然后,跑

g2d.setPaint(tp);

and you're good to go. 而你很高兴。

As @wchargin said, you can use TexturePaint . 正如@wchargin所说,你可以使用TexturePaint Here is an example: 这是一个例子:

public class TexturePanel extends JPanel {

    private TexturePaint paint;

    public TexturePanel(BufferedImage bi) {
        super();
        this.paint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(paint);
        g2.fill(new Rectangle(0, 0, getWidth(), getHeight()));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM