【问题标题】:Fill rectangle with image in Java用Java中的图像填充矩形
【发布时间】:2013-03-06 12:58:06
【问题描述】:

如何使用图像填充以下矩形?谁能帮帮我?

public void paintComponent(Graphics g) {
         setOpaque(false);  
        //Paint a filled rectangle at user's chosen point.
        if (point != null) {
            g.drawRect(0, 0,
                       rectWidth - 1, rectHeight - 1);
            g.setColor(Color.yellow);
            g.fillRect(1, 1,
                       rectWidth - 2, rectHeight - 2);
            }}

我尝试了这段代码,但找不到让它工作的方法:

File imageFile = new File("duck.jpg");
BufferedImage img;
Graphics2D graph = img.createGraphics();
graph.setColor(Color.BLACK);
graph.fill(new Rectangle(1, 2, rectWidth, rectHeight));
graph.dispose();
ImageIO.write(img, "jpg", new File("duck.jpg"));

【问题讨论】:

  • 您创建变量imageFile 是为了什么?还有,你知道dispose是什么意思吗,你看过同名方法的评论吗?
  • 顺便问一下这条线上有NullPointerException吗..Graphics2D graph = img.createGraphics();

标签: java


【解决方案1】:

您必须将图像加载到 Image 对象(如 BufferedImage)中,然后调用

graphics.drawImage()

在该图像上,提供坐标和其他信息。

查看the tutorial了解更多信息

【讨论】:

  • 我已经尝试过你的想法,但它给我一个错误:Image img = Toolkit.getDefaultToolkit().getImage("duck.jpg"); int w = img.getWidth(null); int h = img.getHeight(null); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); //Graphics g = bi.getGraphics(); g.drawImage(img, 0, 0, null);
  • 这不是错误,而是抛出它的代码行。发布错误。
  • Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (-1) and height (-1) cannot be <= 0 和许多其他人
  • 如果宽度未知,getWidth 返回 -1。这意味着图像尚未加载。看看这个stackoverflow.com/questions/3336558/…
猜你喜欢
  • 2012-11-07
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多