Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java2D question.: How can you superimpose an image on another?

 
Darrin Smith
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an application where I scale a thumbnail image to fit inside a preset area that displays it. The image gets stretched to fill up that area, so I would like to place it on a black image to act as a background that has the correct size. That way, the component won't stretch the image since the newly build one will fit exactly.

So, how do you superimpose one image (my thumbnail) over top of another one (the black image)?

THANKS!
 
Ko Wey
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried something like this:


BufferedImage bufferedImage =
new BufferedImage(component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = (Graphics2D)bufferedImage.getGraphics();
g2D.drawImage(thumbnail,0,0,null);


and then in the component's paintComponent()method

public void paintComponent(Graphics g){
if (bufferedImage!=null)
g.drawImage(bufferedImage,0,0,this);
}

the thumbnail will not be enlarged, I think.
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can override the 'getPreferredSize' method in the component that draws the scaled–to–fill image. Add this component to a container with GridBagLayout and set its background to black. The container will expand to fill its parent and show the image component centered within the black field. If you put the container inside a JScrollPane the scrollpane will set its scrollbars with the information it gets (Swing takes care of this) when it calls 'getPreferredSize.'
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way, as mentioned, is to use a BufferedImage. Another is to
have a component that paints one image on top of the other:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic