图像未在面板的左上方绘制

时间:2015-04-13 15:10:13

标签: java graphics2d

当我加载图像时,它不会在左上角加载(如果图像很大以适合窗口大小)。这是因为我缩小了它的大小,如代码所示。虽然我给它的坐标值为0,0但它并没有在那个位置绘制。

import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class photo extends JFrame 
{
Dimension screenwidth=getToolkit().getScreenSize();
int mx=(int)screenwidth.getWidth(); 
int my=(int)screenwidth.getHeight();
BufferedImage picture1;
JLabel label3;
int neww;
int newh;
    public photo() {

    JFrame f = new JFrame("Image Editor v1.0");
    f.setLayout(null);
    try{
        File file=new File("e:\\8.jpg");
            picture1=ImageIO.read(file);
    }catch(Exception e)
    {

    }

    JPanel panel2 = new JPanel();
    panel2.setLayout(null);
    panel2.setBounds(101,20,mx-100,my-20);
    f.add(panel2);
    label3 = new JLabel("");
    label3.setBounds(110,30,mx-110,my-30);
    panel2.add(label3);
    f.setExtendedState(Frame.MAXIMIZED_BOTH);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BufferedImage bi = null;

            if(picture1.getWidth()>mx-110 ||picture1.getHeight()>my-30 )
            {

                 neww= (int) Math.round(picture1.getWidth() * 0.25);
                newh = (int) Math.round(picture1.getHeight() *0.25);
            }
            else
            {
                neww=picture1.getWidth();
                newh=picture1.getHeight();

            }
            bi = new BufferedImage(neww,newh,BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = (Graphics2D) bi.createGraphics();
            g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
            g2d.drawImage(picture1,0,0,neww,newh,0,0,picture1.getWidth(),picture1.getHeight(), null);
           label3.setIcon(new ImageIcon(bi));

    }

public static void main(String[] args) 
{
    new photo();

}

}

1 个答案:

答案 0 :(得分:0)

您可以在g2d.translate(0, 0);g2d.addRenderingHints之间添加g2d.drawImage并尝试使用。

修改

因此,如果您希望图像为101像素和20像素,则应在label3.setBounds(0,0,neww,newh);之后label3.setIcon(new ImageIcon(bi));而不是当前图像。我认为这应该像我刚刚测试的那样工作。