File originalImage = new File("anyImage.jpg");
BufferedImage newImage = null;
try{
newImage = ImageIO.read(originalImage);
//JPanel np = new JPanel();
Graphics2D g2 = null;
// np.paintComponents(g2);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = (getWidth() - size.width)/2;
int y = (getHeight() - size.height)/2;
g2.drawImage(newImage, x, y, this);
if(showClip){
if(clip == null)
clip = new Rectangle(100,100); // set the size of the rectangle
clip.x = (newImage.getWidth() - clip.width)/2;
clip.y = (newImage.getHeight() - clip.height)/2;
int x0 = (newImage.getWidth() - size.width)/2;
int y0 = (newImage.getHeight() - size.height)/2;
if(x < x0 || x + clip.width > x0 + size.width ||
y < y0 || y + clip.height > y0 + size.height);
// return;
clip.setLocation(x, y);
g2.setPaint(Color.RED);
g2.draw(clip);
}
}
catch (IOException ex) {
Logger.getLogger(ImageView.class.getName()).log(Level.SEVERE, null, ex);
}
我的问题是,我们如何在图像上绘制方形图形,这意味着它应该显示在此代码上,
结果应如下图所示: