• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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

 
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!
 
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.
 
Ranch Hand
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.'
 
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:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!