• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • Last Modified:

Images in canvas

Hi!
I have 2 img and I would use them to create my slider. I know I have to use canvas. One img suppose to goes strieght back and force meantime other is not moving.Please show some example.
0
gee
Asked:
gee
1 Solution
 
Sasha_MapaCommented:
Here is an example of a component that draws an image and allows dragging it around with your mouse. From what I understand you want something similar but that moves just around the x OR y axis... should be easy to modify:


public class MyComponent extends Canvas{

  private Image dbImage; // Image for double buffering, to avoid flickering.
  private Image myImage;
  private int imageX=0, imageY=0; // The location of our image;

  private int lastDragX, lastDragY;

  public MyComponent(Image image){
     myImage = image;
  }


  public void update(Graphics g){
     Graphics dbGraphics = getDBGraphics();
     dbGraphics.setColor(getBackground());
     dbGraphics.fillRect(0,0,bounds().width,bounds().height);
     paint(dbGraphics);
     g.drawImage(dbImage,0,0,null);
  }

                       
  public void paint(Graphics g){
    g.drawImage(myImage,imageX,imageY,null);
 }


  public boolean mouseDown(Event e, int x, int y){
     lastDragX = x;
     lastDragY = y;
     return false;
 }


  public boolean mouseDrag(Event e, int x, int y){
     imageX += x-lastDragX;
     imageY += y-lastDragY;
     lastDragX = x;
     lastDragY = y;
     repaint();      
     return false;
  }



                       

  private final Graphics getDBGraphics(){
     if ((dbImage == null) || ((dbImage.getWidth(null)!=(int)getIBounds().getWidth())||
(dbImage.getHeight(null)!=(int)getIBounds().getHeight()))){
       dbImage = createImage((int)Math.max(getIBounds().getWidth(),1),
                                              (int)Math.max(getIBounds().getHeight(),1));
   // Using Math.max is needed because createImage only takes positive
   // values, which seems strange to me, since components can even
   // have negative size.
     }
     return dbImage.getGraphics();
  }

}



Hope this helps, Sasha.

0
 
vladi21Commented:
R u using Swing?
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now