簡體   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