繁体   English   中英

在Java Swing中用模式填充矩形

[英]Fill rectangle with pattern in Java Swing

我知道如何用纯色填充Swing中的矩形:

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

我知道如何用图像填充它:

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

但是如何用一些尺寸为100x100的平铺图案填充尺寸为950x950的矩形?

(图案图像应使用100次)

您正在使用setPaint进入正确的轨道。 但是,您不想将其设置为颜色,而是将其设置为TexturePaint对象。

Java教程

TexturePaint类的模式由BufferedImage类定义。 要创建TexturePaint对象,请指定包含图案的图像以及用于复制和锚定图案的矩形。 以下图像代表此功能: 示例图片

如果您有纹理的BufferedImage ,请创建一个TexturePaint如下所示:

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

给定的矩形表示要平铺的源图像的区域。

构造函数JavaDoc就在这里

然后,跑

g2d.setPaint(tp);

而你很高兴。

正如@wchargin所说,你可以使用TexturePaint 这是一个例子:

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