Search Results

Search found 258 results on 11 pages for 'drawimage'.

Page 4/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • JFrame does not refresh after deleting an image

    - by dajackal
    Hi! I'm working for the first time with images in a JFrame, and I have some problems. I succeeded in putting an image on my JFrame, and now i want after 2 seconds to remove my image from the JFrame. But after 2 seconds, the image does not disappear, unless I resize the frame or i minimize and after that maximize the frame. Help me if you can. Thanks. Here is the code: File f = new File("2.jpg"); System.out.println("Picture " + f.getAbsolutePath()); BufferedImage image = ImageIO.read(f); MyBufferedImage img = new MyBufferedImage(image); img.resize(400, 300); img.setSize(400, 300); img.setLocation(50, 50); getContentPane().add(img); this.setSize(600, 400); this.setLocationRelativeTo(null); this.setVisible(true); Thread.sleep(2000); System.out.println("2 seconds over"); getContentPane().remove(img); Here is the MyBufferedImage class: public class MyBufferedImage extends JComponent{ private BufferedImage image; private int nPaint; private int avgTime; private long previousSecondsTime; public MyBufferedImage(BufferedImage b) { super(); this.image = b; this.nPaint = 0; this.avgTime = 0; this.previousSecondsTime = System.currentTimeMillis(); } @Override public void paintComponent(Graphics g) { Graphics2D g2D = (Graphics2D) g; g2D.setColor(Color.BLACK); g2D.fillRect(0, 0, this.getWidth(), this.getHeight()); long currentTimeA = System.currentTimeMillis(); //g2D.drawImage(this.image, 320, 0, 0, 240, 0, 0, 640, 480, null); g2D.drawImage(image, 0,0, null); long currentTimeB = System.currentTimeMillis(); this.avgTime += currentTimeB - currentTimeA; this.nPaint++; if (currentTimeB - this.previousSecondsTime > 1000) { System.out.format("Drawn FPS: %d\n", nPaint++); System.out.format("Average time of drawings in the last sec.: %.1f ms\n", (double) this.avgTime / this.nPaint++); this.previousSecondsTime = currentTimeB; this.avgTime = 0; this.nPaint = 0; } } }

    Read the article

  • 2d java Graphics

    - by LukeG
    I am new to java 2d graphics and I have problem handling mouseclick event. Is it possible for you to tell me why there is nothing going on after updating mouse status to clicked ? What I want to do is to change the image in array at 0 2 to another image. Nothing happens tho. Thanks for your help in advance. import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.*; import java.awt.*; import javax.swing.ImageIcon; import javax.swing.*; public class Board extends JPanel implements MouseListener { private static boolean[] keyboardState = new boolean[525]; private static boolean[] mouseState = new boolean[3]; private static Image[][] images; Image house; int w = 0; int h = 0; int xPos; int yPos; ImageIcon ii = new ImageIcon(this.getClass().getResource("house.gif")); ImageIcon iii = new ImageIcon(this.getClass().getResource("house1.gif")); public Board() { house = ii.getImage(); h = house.getHeight(null); w = house.getWidth(null); images = new Image[10][10]; for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { images[i][j] = house; } } } public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { g2d.drawImage(images[i][j],w*i,h*j,null); } } //g2d.drawImage(house,15,15,null); } public void checkMouse() { if(mouseState[0]) { images[0][2] = iii.getImage(); repaint(); super.repaint(); } } @Override public void mousePressed(MouseEvent e) { mouseKeyStatus(e, true); checkMouse(); } @Override public void mouseReleased(MouseEvent e) { mouseKeyStatus(e, false); repaint(); } public static boolean mouseButtonState(int button) { return mouseState[button - 1]; } private void mouseKeyStatus(MouseEvent e, boolean status) { if(e.getButton() == MouseEvent.BUTTON1) mouseState[0] = status; else if(e.getButton() == MouseEvent.BUTTON2) mouseState[1] = status; else if(e.getButton() == MouseEvent.BUTTON3) mouseState[2] = status; }

    Read the article

  • Scalable images in Java

    - by CodeGuy
    I anticipate using some images in my Java application. These images will be drawn onto my JPanel using g.drawImage(). The JPanel is resizable and the images should scale as the JPanel increases/decreases in size Two questions: What image format is best for this type of desired scalable image? For instance, in this application, an image of size 100x100 may be scaled into an image of size 30x30 or 10x10 or 300x300. How can I write code to do this scaling?

    Read the article

  • Smooth animation on a persistently refreshing canvas

    - by Neurofluxation
    Yo everyone! I have been working on an Isometric Tile Game Engine in HTML5/Canvas for a little while now and I have a complete working game. Earlier today I looked back over my code and thought: "hmm, let's try to get this animated smoothly..." And since then, that is all I have tried to do. The problem I would like the character to actually "slide" from tile to tile - but the canvas redrawing doesn't allow this - does anyone have any ideas....? Code and fiddle below... Fiddle with it! http://jsfiddle.net/neuroflux/n7VAu/ <html> <head> <title>tileEngine - Isometric</title> <style type="text/css"> * { margin: 0px; padding: 0px; font-family: arial, helvetica, sans-serif; font-size: 12px; cursor: default; } </style> <script type="text/javascript"> var map = Array( //land [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]], [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]] ); var tileDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/land.png"); var charDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/mario.png"); var objectDict = Array("http://www.wikiword.co.uk/release-candidate/canvas/tileEngine/rock.png"); //last is one more var objectImg = new Array(); var charImg = new Array(); var tileImg = new Array(); var loaded = 0; var loadTimer; var ymouse; var xmouse; var eventUpdate = 0; var playerX = 0; var playerY = 0; function loadImg(){ //preload images and calculate the total loading time for(var i=0;i<tileDict.length;i++){ tileImg[i] = new Image(); tileImg[i].src = tileDict[i]; tileImg[i].onload = function(){ loaded++; } } i = 0; for(var i=0;i<charDict.length;i++){ charImg[i] = new Image(); charImg[i].src = charDict[i]; charImg[i].onload = function(){ loaded++; } } i = 0; for(var i=0;i<objectDict.length;i++){ objectImg[i] = new Image(); objectImg[i].src = objectDict[i]; objectImg[i].onload = function(){ loaded++; } } } function checkKeycode(event) { //key pressed var keycode; if(event == null) { keyCode = window.event.keyCode; } else { keyCode = event.keyCode; } switch(keyCode) { case 38: //left if(!map[playerX-1][playerY][1] > 0){ playerX--; } break; case 40: //right if(!map[playerX+1][playerY][1] > 0){ playerX++; } break; case 39: //up if(!map[playerX][playerY-1][1] > 0){ playerY--; } break; case 37: //down if(!map[playerX][playerY+1][1] > 0){ playerY++; } break; default: break; } } function loadAll(){ //load the game if(loaded == tileDict.length + charDict.length + objectDict.length){ clearInterval(loadTimer); loadTimer = setInterval(gameUpdate,100); } } function drawMap(){ //draw the map (in intervals) var tileH = 25; var tileW = 50; mapX = 80; mapY = 10; for(i=0;i<map.length;i++){ for(j=0;j<map[i].length;j++){ var drawTile= map[i][j][0]; var xpos = (i-j)*tileH + mapX*4.5; var ypos = (i+j)*tileH/2+ mapY*3.0; ctx.drawImage(tileImg[drawTile],xpos,ypos); if(i == playerX && j == playerY){ you = ctx.drawImage(charImg[0],xpos,ypos-(charImg[0].height/2)); } } } } function init(){ //initialise the main functions and even handlers ctx = document.getElementById('main').getContext('2d'); loadImg(); loadTimer = setInterval(loadAll,10); document.onkeydown = checkKeycode; } function gameUpdate() { //update the game, clear canvas etc ctx.clearRect(0,0,904,460); ctx.fillStyle = "rgba(255, 255, 255, 1.0)"; //assign color drawMap(); } </script> </head> <body align="center" style="text-align: center;" onload="init()"> <canvas id="main" width="904" height="465"> <h1 style="color: white; font-size: 24px;">I'll be damned, there be no HTML5 &amp; canvas support on this 'ere electronic machine!<sub>This game, jus' plain ol' won't work!</sub></h1> </canvas> </body> </html>

    Read the article

  • App using MonoTouch Core Graphics mysteriously crashes

    - by Stephen Ashley
    My app launches with a view controller and a simple view consisting of a button and a subview. When the user touches the button, the subview is populated with scrollviews that display the column headers, row headers, and cells of a spreadsheet. To draw the cells, I use CGBitmapContext to draw the cells, generate an image, and then put the image into the imageview contained in the scrollview that displays the cells. When I run the app on the iPad, it displays the cells just fine, and the scrollview lets the user scroll around in the spreadsheet without any problems. If the user touches the button a second time, the spreadsheet redraws and continues to work perfectly, If, however, the user touches the button a third time, the app crashes. There is no exception information display in the Application Output window. My first thought was that the successive button pushes were using up all the available memory, so I overrode the DidReceiveMemoryWarning method in the view controller and used a breakpoint to confirm that this method was not getting called. My next thought was that the CGBitmapContext was not getting released and looked for a Monotouch equivalent of Objective C's CGContextRelease() function. The closest I could find was the CGBitmapContext instance method Dispose(), which I called, without solving the problem. In order to free up as much memory as possible (in case I was somehow running out of memory without tripping a warning), I tried forcing garbage collection each time I finished using a CGBitmapContext. This made the problem worse. Now the program would crash moments after displaying the spreadsheet the first time. This caused me to wonder whether the Garbage Collector was somehow collecting something necessary to the continued display of graphics on the screen. I would be grateful for any suggestions on further avenues to investigate for the cause of these crashes. I have included the source code for the SpreadsheetView class. The relevant method is DrawSpreadsheet(), which is called when the button is touched. Thank you for your assistance on this matter. Stephen Ashley public class SpreadsheetView : UIView { public ISpreadsheetMessenger spreadsheetMessenger = null; public UIScrollView cellsScrollView = null; public UIImageView cellsImageView = null; public SpreadsheetView(RectangleF frame) : base() { Frame = frame; BackgroundColor = Constants.backgroundBlack; AutosizesSubviews = true; } public void DrawSpreadsheet() { UInt16 RowHeaderWidth = spreadsheetMessenger.RowHeaderWidth; UInt16 RowHeaderHeight = spreadsheetMessenger.RowHeaderHeight; UInt16 RowCount = spreadsheetMessenger.RowCount; UInt16 ColumnHeaderWidth = spreadsheetMessenger.ColumnHeaderWidth; UInt16 ColumnHeaderHeight = spreadsheetMessenger.ColumnHeaderHeight; UInt16 ColumnCount = spreadsheetMessenger.ColumnCount; // Add the corner UIImageView cornerView = new UIImageView(new RectangleF(0f, 0f, RowHeaderWidth, ColumnHeaderHeight)); cornerView.BackgroundColor = Constants.headingColor; CGColorSpace cornerColorSpace = null; CGBitmapContext cornerContext = null; IntPtr buffer = Marshal.AllocHGlobal(RowHeaderWidth * ColumnHeaderHeight * 4); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory."); try { cornerColorSpace = CGColorSpace.CreateDeviceRGB(); cornerContext = new CGBitmapContext (buffer, RowHeaderWidth, ColumnHeaderHeight, 8, 4 * RowHeaderWidth, cornerColorSpace, CGImageAlphaInfo.PremultipliedFirst); cornerContext.SetFillColorWithColor(Constants.headingColor.CGColor); cornerContext.FillRect(new RectangleF(0f, 0f, RowHeaderWidth, ColumnHeaderHeight)); cornerView.Image = UIImage.FromImage(cornerContext.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (cornerContext != null) { cornerContext.Dispose(); cornerContext = null; } if (cornerColorSpace != null) { cornerColorSpace.Dispose(); cornerColorSpace = null; } } cornerView.Image = DrawBottomRightCorner(cornerView.Image); AddSubview(cornerView); // Add the cellsScrollView cellsScrollView = new UIScrollView (new RectangleF(RowHeaderWidth, ColumnHeaderHeight, Frame.Width - RowHeaderWidth, Frame.Height - ColumnHeaderHeight)); cellsScrollView.ContentSize = new SizeF (ColumnCount * ColumnHeaderWidth, RowCount * RowHeaderHeight); Size iContentSize = new Size((int)cellsScrollView.ContentSize.Width, (int)cellsScrollView.ContentSize.Height); cellsScrollView.BackgroundColor = UIColor.Black; AddSubview(cellsScrollView); CGColorSpace colorSpace = null; CGBitmapContext context = null; CGGradient gradient = null; UIImage image = null; int bytesPerRow = 4 * iContentSize.Width; int byteCount = bytesPerRow * iContentSize.Height; buffer = Marshal.AllocHGlobal(byteCount); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); context = new CGBitmapContext (buffer, iContentSize.Width, iContentSize.Height, 8, 4 * iContentSize.Width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); float[] components = new float[] {.75f, .75f, .75f, 1f, .25f, .25f, .25f, 1f}; float[] locations = new float[]{0f, 1f}; gradient = new CGGradient(colorSpace, components, locations); PointF startPoint = new PointF(0f, (float)iContentSize.Height); PointF endPoint = new PointF((float)iContentSize.Width, 0f); context.DrawLinearGradient(gradient, startPoint, endPoint, 0); context.SetLineWidth(Constants.lineWidth); context.BeginPath(); for (UInt16 i = 1; i <= RowCount; i++) { context.MoveTo (0f, iContentSize.Height - i * RowHeaderHeight + (Constants.lineWidth/2)); context.AddLineToPoint((float)iContentSize.Width, iContentSize.Height - i * RowHeaderHeight + (Constants.lineWidth/2)); } for (UInt16 j = 1; j <= ColumnCount; j++) { context.MoveTo((float)j * ColumnHeaderWidth - Constants.lineWidth/2, (float)iContentSize.Height); context.AddLineToPoint((float)j * ColumnHeaderWidth - Constants.lineWidth/2, 0f); } context.StrokePath(); image = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (gradient != null) { gradient.Dispose(); gradient = null; } if (context != null) { context.Dispose(); context = null; } if (colorSpace != null) { colorSpace.Dispose(); colorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } UIImage finalImage = ActivateCell(1, 1, image); finalImage = ActivateCell(0, 0, finalImage); cellsImageView = new UIImageView(finalImage); cellsImageView.Frame = new RectangleF(0f, 0f, iContentSize.Width, iContentSize.Height); cellsScrollView.AddSubview(cellsImageView); } private UIImage ActivateCell(UInt16 column, UInt16 row, UIImage backgroundImage) { UInt16 ColumnHeaderWidth = (UInt16)spreadsheetMessenger.ColumnHeaderWidth; UInt16 RowHeaderHeight = (UInt16)spreadsheetMessenger.RowHeaderHeight; CGColorSpace cellColorSpace = null; CGBitmapContext cellContext = null; UIImage cellImage = null; IntPtr buffer = Marshal.AllocHGlobal(4 * ColumnHeaderWidth * RowHeaderHeight); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: ActivateCell()"); try { cellColorSpace = CGColorSpace.CreateDeviceRGB(); // Create a bitmap the size of a cell cellContext = new CGBitmapContext (buffer, ColumnHeaderWidth, RowHeaderHeight, 8, 4 * ColumnHeaderWidth, cellColorSpace, CGImageAlphaInfo.PremultipliedFirst); // Paint it white cellContext.SetFillColorWithColor(UIColor.White.CGColor); cellContext.FillRect(new RectangleF(0f, 0f, ColumnHeaderWidth, RowHeaderHeight)); // Convert it to an image cellImage = UIImage.FromImage(cellContext.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (cellContext != null) { cellContext.Dispose(); cellContext = null; } if (cellColorSpace != null) { cellColorSpace.Dispose(); cellColorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } // Draw the border on the cell image cellImage = DrawBottomRightCorner(cellImage); CGColorSpace colorSpace = null; CGBitmapContext context = null; Size iContentSize = new Size((int)backgroundImage.Size.Width, (int)backgroundImage.Size.Height); buffer = Marshal.AllocHGlobal(4 * iContentSize.Width * iContentSize.Height); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: ActivateCell()."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); // Set up a bitmap context the size of the whole grid context = new CGBitmapContext (buffer, iContentSize.Width, iContentSize.Height, 8, 4 * iContentSize.Width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); // Draw the original grid into the bitmap context.DrawImage(new RectangleF(0f, 0f, iContentSize.Width, iContentSize.Height), backgroundImage.CGImage); // Draw the cell image into the bitmap context.DrawImage(new RectangleF(column * ColumnHeaderWidth, iContentSize.Height - (row + 1) * RowHeaderHeight, ColumnHeaderWidth, RowHeaderHeight), cellImage.CGImage); // Convert the bitmap back to an image backgroundImage = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (context != null) { context.Dispose(); context = null; } if (colorSpace != null) { colorSpace.Dispose(); colorSpace = null; } // GC.Collect(); //GC.WaitForPendingFinalizers(); } return backgroundImage; } private UIImage DrawBottomRightCorner(UIImage image) { int width = (int)image.Size.Width; int height = (int)image.Size.Height; float lineWidth = Constants.lineWidth; CGColorSpace colorSpace = null; CGBitmapContext context = null; UIImage returnImage = null; IntPtr buffer = Marshal.AllocHGlobal(4 * width * height); if (buffer == IntPtr.Zero) throw new OutOfMemoryException("Out of memory: DrawBottomRightCorner()."); try { colorSpace = CGColorSpace.CreateDeviceRGB(); context = new CGBitmapContext (buffer, width, height, 8, 4 * width, colorSpace, CGImageAlphaInfo.PremultipliedFirst); context.DrawImage(new RectangleF(0f, 0f, width, height), image.CGImage); context.BeginPath(); context.MoveTo(0f, (int)(lineWidth/2f)); context.AddLineToPoint(width - (int)(lineWidth/2f), (int)(lineWidth/2f)); context.AddLineToPoint(width - (int)(lineWidth/2f), height); context.SetLineWidth(Constants.lineWidth); context.SetStrokeColorWithColor(UIColor.Black.CGColor); context.StrokePath(); returnImage = UIImage.FromImage(context.ToImage()); } finally { Marshal.FreeHGlobal(buffer); if (context != null){ context.Dispose(); context = null;} if (colorSpace != null){ colorSpace.Dispose(); colorSpace = null;} // GC.Collect(); //GC.WaitForPendingFinalizers(); } return returnImage; } }

    Read the article

  • Getting problem in collision detection in Java Game

    - by chetans
    Hi I am developing Spaceship Game in which i am getting problem in collision detection of moving images Game has a spaceship and number of asteroids(obstacles) i want to detect the collision between them How can i do this?`package Game; import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.net.MalformedURLException; import java.net.URL; public class ThreadInApplet extends Applet implements KeyListener { private static final long serialVersionUID = 1L; Image[] asteroidImage; Image spaceshipImage; int[] XPosObst,YPosObst; int numberOfObstacles=0,XPosOfSpaceship,YPosOfSpaceship; int spaceButtnCntr=0,noOfObstaclesLevel=20; boolean gameStart=false,collideUp=false,collideDown=false,collideLeft=false,collideRight=false; private Image offScreenImage; private Dimension offScreenSize,d; private Graphics offScreenGraphics; int speedObstacles=1; String spaceshipImagePath="images/spaceship.png",obstacleImagepath="images/asteroid.png"; String buttonToStart="Press Space to start"; public void init() { try { asteroidImage=new Image[noOfObstaclesLevel]; XPosObst=new int[noOfObstaclesLevel]; YPosObst=new int[noOfObstaclesLevel]; XPosOfSpaceship=getWidth()/2-35; YPosOfSpaceship=getHeight()-100; spaceshipImage=getImage(new URL(getCodeBase(),spaceshipImagePath)); for(int i=0;i<noOfObstaclesLevel;i++) { asteroidImage[i]=getImage(new URL(getCodeBase(),obstacleImagepath)); XPosObst[i]=(int) (Math.random()*700); YPosObst[i]=0; } MediaTracker tracker = new MediaTracker (this); for(int i=0;i<noOfObstaclesLevel;i++) { tracker.addImage (asteroidImage[i], 0); } } catch (MalformedURLException e) { e.printStackTrace(); } setBackground(Color.black); addKeyListener(this); } public void paint(Graphics g) { g.setColor(Color.white); if(gameStart==false) { g.drawString(buttonToStart, (getWidth()/2)-60, getHeight()/2); } g.drawString("HEADfitted Solutions Pvt.Ltd.", (getWidth()/2)-80, getHeight()-20); for(int n=0;n<numberOfObstacles;n++) { if(n>0) g.drawImage(asteroidImage[n],XPosObst[n],YPosObst[n],this); } g.drawImage(spaceshipImage,XPosOfSpaceship,YPosOfSpaceship,this); } @SuppressWarnings("deprecation") public void update(Graphics g) { d = size(); if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) { offScreenImage = createImage(d.width, d.height); offScreenSize = d; offScreenGraphics = offScreenImage.getGraphics(); } offScreenGraphics.clearRect(0, 0, d.width, d.height); paint(offScreenGraphics); g.drawImage(offScreenImage, 0, 0, null); } public void keyReleased(KeyEvent arg0){} public void keyTyped(KeyEvent arg0) {} Thread mainThread=new Thread() { synchronized public void run () { try { //System.out.println("in main thread"); if (gameStart==true) { moveObstacles.start(); if(collide()==false) { createObsThread.start(); } } } catch (Exception e) { e.printStackTrace(); } } }; Thread createObsThread=new Thread() { synchronized public void run () { if (spaceButtnCntr==1) { if (collide()==false) { for(int g=0;g<noOfObstaclesLevel;g++) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } numberOfObstacles++; } } } } }; Thread moveObstacles=new Thread() // Moving Obstacle images downwards after every 10 ms { synchronized public void run () { while(YPosObst[19]!=600) { if (collide()==false) { //createObsThread.start(); for(int l=0;l } repaint(); try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; public void keyPressed(KeyEvent e) { if(e.getKeyCode()==32) { gameStart=true; spaceButtnCntr++; if (spaceButtnCntr==1) { mainThread.start(); } } if(gameStart==true) { if(e.getKeyCode()==37 && collideLeft==false)//Spaceship movement left { new Thread () { synchronized public void run () { XPosOfSpaceship-=10; repaint(); } }.start(); } if(e.getKeyCode()==38 && collideUp==false)//Spaceship movement up { new Thread () { synchronized public void run () { YPosOfSpaceship-=10; repaint(); } }.start(); } if(e.getKeyCode()==39 && collideRight==false)//Spaceship movement right { new Thread () { synchronized public void run () { XPosOfSpaceship+=10; repaint(); } }.start(); } if(e.getKeyCode()==40 && collideDown==false)//Spaceship movement down { new Thread () { synchronized public void run () { YPosOfSpaceship+=10; repaint(); } }.start(); } } } /*public boolean collide() { int x0, y0, w0, h0, x2, y2, w2, h2; x0=XPosOfSpaceship; y0=YPosOfSpaceship; h0=spaceshipImage.getHeight(null); w0=spaceshipImage.getWidth(null); for(int i=0;i<20;i++) { x2=XPosObst[i]; y2=YPosObst[i]; h2=asteroidImage[i].getHeight(null); w2=asteroidImage[i].getWidth(null); if ((x0 > (x2 + w2)) || ((x0 + w0) < x2)) return false; System.out.println(x2+" "+y2+" "+h2+" "+w2); if ((y0 > (y2 + h2)) || ((y0 + h0) < y2)) return false; } return true; }*/ public boolean collide() { int x1,y1,x2,y2,x3,y3,x4,y4; //coordinates of obstacles int a1,b1,a2,b2,a3,b3,a4,b4; //coordinates of spaceship a1 =XPosOfSpaceship; b1=YPosOfSpaceship; a2=a1+spaceshipImage.getWidth(this); b2=b1; a3=a1; b3=b1+spaceshipImage.getHeight(this); a4=a2; b4=b3; for(int a=0;a if(x1>=a1 && x1<=a2 && x1<=b3 && x1>=b1) return (true); if(x2>=a1 && x2<=a2 && x2<=b3 && x2>=b1) return(true); //********checking asteroid touch spaceship from up direction******** if(y3==b1 && x4>=a1 && x4<=a2) { collideUp = true; return(true); } if(y3==b1 && x3>=a1 && x3<=a2) { collideUp = true; return(true); } //********checking asteroid touch spaceship from left direction****** if(x2==a1 && y4>=b1 && y4<=b3) { collideLeft=true; return(true); } if(x2==a1 && y2>=b1 && y2<=b3) { collideLeft=true; return(true); } //********checking asteroid touch spaceship from right direction***** if(x1==a2 && y3>=b2 && y3<=b4) { collideRight=true; return(true); } if(x1==a2 && y1>=b2 && y1<=b4) { collideRight=true; return(true); } //********checking asteroid touch spaceship from down direction***** if(y1==b3 && x2>=a3 && x2<=a4) { collideDown=true; return(true); } if(y1==b3 && x1>=a3 && x1<=a4) { collideDown=true; return(true); } else { collideUp=false; collideDown=false; collideLeft=false; collideRight=false; } } return(false); } } `

    Read the article

  • Getting problem in threading in JAVA

    - by chetans
    In this program i want to stop GenerateImage & MovingImage Thread both... And i want to start those threads from begining. Can u send me the solution? Here is the code........ package Game; import java.applet.Applet; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.net.MalformedURLException; import java.net.URL; public class ThreadInApplet extends Applet implements KeyListener { private static final long serialVersionUID = 1L; Image[] asteroidImage; Image spaceshipImage; String levelstr="Easy Level"; int[] XPos,YPos; int number=0,XPosOfSpaceship,YPosOfSpaceship,NoOfObstacles=5,speed=1,level=1,spaceBtnPressdCntr=0; boolean gameStart=false,pauseGame=false,collideUp=false,collideDown=false,collideLeft=false,collideRight=false; private Image offScreenImage; private Dimension offScreenSize; private Graphics offScreenGraphics; Thread GenerateImages,MoveImages; public void init() { try { GenerateImages=new Thread () //thread to create obstacles { synchronized public void run () { for(int g=0;g<NoOfObstacles;g++) { try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } number++; // Temporary counter to count the no of obstacles created } } } ; MoveImages=new Thread () //thread to move obstacles { @SuppressWarnings("deprecation") synchronized public void run () { while(YPos[NoOfObstacles-1]!=600) { pauseGame=false; if(collide()==true) { GenerateImages.suspend(); repaint(); } else GenerateImages.resume(); for(int l=0;l<number;l++) { if(collide()==false) YPos[l]++; else GenerateImages.suspend(); } repaint(); try { sleep(speed); } catch (InterruptedException e) { e.printStackTrace(); } } if(YPos[NoOfObstacles-1]>=600) //level complete state { level++; try { levelUpdation(level); System.out.println("aahe"); } catch (MalformedURLException e) { e.printStackTrace(); } repaint(); } } }; initialPos(); spaceshipImage=getImage(new URL(getCodeBase(),"images/space.png")); for(int i=0;i<NoOfObstacles;i++) { asteroidImage[i]=getImage(new URL(getCodeBase(),"images/asteroid.png")); XPos[i]=(int) (Math.random()*700); YPos[i]=0; } MediaTracker tracker = new MediaTracker (this); for(int i=0;i<NoOfObstacles;i++) { tracker.addImage (asteroidImage[i], 0); } } catch (MalformedURLException e) { e.printStackTrace(); } setBackground(Color.black); addKeyListener(this); } //Sets initial positions of spaceship & obstacle images------------------------------------------------------ public void initialPos() throws MalformedURLException { asteroidImage=new Image[NoOfObstacles]; XPos=new int[NoOfObstacles]; YPos=new int[NoOfObstacles]; XPosOfSpaceship=getWidth()/2-35; YPosOfSpaceship=getHeight()-100; collideUp = false; collideDown=false; collideLeft=false; collideRight=false; } //level finished updations------------------------------------------------------------------------------ @SuppressWarnings("deprecation") public void levelUpdation(int level) throws MalformedURLException { NoOfObstacles=NoOfObstacles+20; speed=speed-3; System.out.println(NoOfObstacles+" "+speed); pauseGame=true; initialPos(); repaint(); } //paint method of graphics to print the messages--------------------------------------------------------- public void paint(Graphics g) { g.setColor(Color.white); if(gameStart==false) { g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); } if(level>1) { if(level==2) levelstr="Medium Level"; else levelstr="High Level"; g.drawString("Level Complete ", (getWidth()/2)-15, getHeight()/2); g.drawString(levelstr, (getWidth()/2), getHeight()/2+20); //g.drawString("SPACE to start", (getWidth()/2)-15, getHeight()/2+40); } for(int n=0;n<number;n++) { if(n>0) g.drawImage(asteroidImage[n],XPos[n],YPos[n],this); } g.drawImage(spaceshipImage,XPosOfSpaceship,YPosOfSpaceship,this); } //update method of graphics to print the messages--------------------------------------------------------- @SuppressWarnings("deprecation") public void update(Graphics g) { Dimension d = size(); if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) { offScreenImage = createImage(d.width, d.height); offScreenSize = d; offScreenGraphics = offScreenImage.getGraphics(); } offScreenGraphics.clearRect(0, 0, d.width, d.height); paint(offScreenGraphics); g.drawImage(offScreenImage, 0, 0, null); } public void keyReleased(KeyEvent arg0){} public void keyTyped(KeyEvent arg0) {} //---------------------Key pressed event to start game & to move the spaceship-------------------------------------- public void keyPressed(KeyEvent e) { if(e.getKeyCode()==32) { spaceBtnPressdCntr++; if(spaceBtnPressdCntr==1) { gameStart=true; GenerateImages.start(); MoveImages.start(); } } if(gameStart==true) { if(e.getKeyCode()==37) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideLeft == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship>0) XPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==38) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideUp == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship>10) YPosOfSpaceship--; } } repaint(); } }.start(); } if(e.getKeyCode()==39) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideRight == true) { GenerateImages.suspend(); } else { if(XPosOfSpaceship<750) XPosOfSpaceship++; } } repaint(); } }.start(); } if(e.getKeyCode()==40) { new Thread () { @SuppressWarnings("deprecation") synchronized public void run () { for(int cnt1=1;cnt1<=10;cnt1++) { if(collide()==true && collideDown == true) { GenerateImages.suspend(); } else { if(YPosOfSpaceship<550) YPosOfSpaceship++; } } repaint(); } }.start(); } } } //------------------------------Collision checking between Spaceship & obstacles------------------------------ public boolean collide() { int x1,y1,x2,y2,x3,y3,x4,y4; //coordinates of obstacles int a1,b1,a2,b2,a3,b3,a4,b4; //coordinates of spaceship a1 =XPosOfSpaceship; b1=YPosOfSpaceship; a2=a1+spaceshipImage.getWidth(this); b2=b1; a3=a1; b3=b1+spaceshipImage.getHeight(this); a4=a2; b4=b3; for(int a=0;a<number;a++) { x1 =XPos[a]; y1=YPos[a]; x2=x1+asteroidImage[a].getWidth(this); y2=y1; x3=x1; y3=y1+asteroidImage[a].getHeight(this); x4=x2; y4=y3; /********checking asteroid touch spaceship from up direction********/ if(y3==b1 && x4>=a1 && x4<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } if(y3==b1 && x3>=a1 && x3<=a2) { collideUp = true; collideDown=false; collideLeft=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from left direction******/ if(x2==a1 && y4>=b1 && y4<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } if(x2==a1 && y2>=b1 && y2<=b3) { collideLeft=true; collideUp = false; collideDown=false; collideRight=false; return(true); } /********checking asteroid touch spaceship from right direction*****/ if(x1==a2 && y3>=b2 && y3<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } if(x1==a2 && y1>=b2 && y1<=b4) { collideRight=true; collideLeft=false; collideUp = false; collideDown=false; return(true); } /********checking asteroid touch spaceship from down direction*****/ if(y1==b3 && x2>=a3 && x2<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } if(y1==b3 && x1>=a3 && x1<=a4) { collideDown=true; collideRight=false; collideLeft=false; collideUp = false; return(true); } } return(false); } }

    Read the article

  • How to properly scroll a 2D tilemap?

    - by Sri Harsha Chilakapati
    Hello and I'm trying to make my own game engine in Java. I have completed all the necessary ones but I can't figure it out with the TileGame class. It just can't scroll. Also there are no exceptions. Here I'm listing the code. TileGame.java @Override public void draw(Graphics2D g) { if (back!=null){ back.render(g); } if (follower!=null){ follower.render(g); follower.draw(g); } for (int i=0; i<actors.size(); i++){ Actor actor = actors.get(i); if (actor!=follower&&getVisibleRect().intersects(actor.getBounds())){ g.drawImage(actor.getAnimation().getFrameImage(), actor.x - OffSetX, actor.y - OffSetY, null); actor.draw(g); } } } /** * This method returns the visible rectangle * @return The visible rectangle */ public Rectangle getVisibleRect(){ return new Rectangle(OffSetX, OffSetY, global.WIDTH, global.HEIGHT); } @Override public void update(){ if (follower!=null){ if (scrollHorizontally){ OffSetX = global.WIDTH/2 - Math.round((float)follower.x) - tileSize; OffSetX = Math.min(OffSetX, 0); OffSetX = Math.max(OffSetX, global.WIDTH - mapWidth); } if (scrollVertically){ OffSetY = global.HEIGHT/2 - Math.round((float)follower.y) - tileSize; OffSetY = Math.min(OffSetY, 0); OffSetY = Math.max(OffSetY, global.HEIGHT - mapHeight); } } for (int i=0; i<actors.size(); i++){ Actor actor1 = actors.get(i); if (getVisibleRect().contains(actor1.x, actor1.y)){ actor1.update(); for (int j=0; j<actors.size(); j++){ Actor actor2 = actors.get(j); if (actor1.isCollidingWith(actor2)){ actor1.collision(actor2); actor2.collision(actor1); } } } } } but the problem is that all the actors are working, but it just won't scroll. Help Please.. Thanks in Advance.

    Read the article

  • Z axis in isometric tilemap

    - by gyhgowvi
    I'm experimenting with isometric tile maps in JavaScript and HTML5 Canvas. I'm storing tile map data in JavaScript 2D array. // 0 - Grass // 1 - Dirt // ... var mapData = [ [0, 0, 0, 0, 0], [0, 0, 1, 0, 0, ... ] and draw for(var i = 0; i < mapData.length; i++) { for(var j = 0; j < mapData[i].length; j++) { var p = iso2screen(i, j, 0); // X, Y, Z context.drawImage(tileArray[mapData[i][j]], p.x, p.y); } } but this function mean's all tile Z axis is equal to zero. var p = iso2screen(i, j, 0); Maybe anyone have idea and how to do something like mapData[0][0] Z axis equal to 3 mapData[5][5] Z axis equal to 5? I have idea: Write function for grass, dirt and store this function to 2D array and draw and later mapData[0][0].setZ(3); But it is good idea to write functions for each tiles?

    Read the article

  • Running multiple image manipulations in parallel causing OutOfMemory exception

    - by Tom
    I am working on a site where I need to be able to split and image around 4000x6000 into 4 parts (amongst many other tasks) and I need this to be as quick as possible for multiple users. My current code for doing this is var bitmaps = new RenderTargetBitmap[elements.Length]; using (var stream = blobService.Stream(key)) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = stream; bi.EndInit(); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; TransformGroup transformGroup = new TransformGroup(); TranslateTransform translateTransform = new TranslateTransform(); translateTransform.X = -element.Left; translateTransform.Y = -element.Top; transformGroup.Children.Add(translateTransform); DrawingVisual vis = new DrawingVisual(); DrawingContext cont = vis.RenderOpen(); cont.PushTransform(transformGroup); cont.DrawImage(bi, new Rect(new Size(bi.PixelWidth, bi.PixelHeight))); cont.Close(); RenderTargetBitmap rtb = new RenderTargetBitmap(element.Width, element.Height, 96d, 96d, PixelFormats.Default); rtb.Render(vis); bitmaps[i] = rtb; } } for (var i = 0; i < bitmaps.Length; i++) { using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmaps[i])); encoder.Save(ms); var regionKey = WebPath.Variant(key, elements[i].Id); saveBlobService.Save("image/png", regionKey, ms); } } I am running multiple threads which take jobs off a queue. I am finding that if this part of code is hit by 4 threads at once I get an OutOfMemory exception. I can stop this happening by wrapping all the code above in a lock(obj) but this isn't ideal. I have tried wrapping just the first using block (where the file is read from disk and split) but I still get the out of memory exceptions (this part of the code executes quite quickly). I this normal considering the amount of memory this should be taking up? Are there any optimisations I could make? Can I increase the memory available? UPDATE: My new code as per Moozhe's help public static void GenerateRegions(this IBlobService blobService, string key, Element[] elements) { using (var stream = blobService.Stream(key)) { foreach (var element in elements) { stream.Position = 0; BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.SourceRect = new Int32Rect(element.Left, element.Top, element.Width, element.Height); bi.StreamSource = stream; bi.EndInit(); DrawingVisual vis = new DrawingVisual(); DrawingContext cont = vis.RenderOpen(); cont.DrawImage(bi, new Rect(new Size(element.Width, element.Height))); cont.Close(); RenderTargetBitmap rtb = new RenderTargetBitmap(element.Width, element.Height, 96d, 96d, PixelFormats.Default); rtb.Render(vis); using (MemoryStream ms = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(ms); var regionKey = WebPath.Variant(key, element.Id); blobService.Save("image/png", regionKey, ms); } } } }

    Read the article

  • I can't scroll my tilemap ... HELP!

    - by Sri Harsha Chilakapati
    Hello and I'm trying to make my own game engine in Java. I have completed all the necessary ones but I can't figure it out with the TileGame class. It just can't scroll. Also there are no exceptions. Here I'm listing the code. TileGame.java @Override public void draw(Graphics2D g) { if (back!=null){ back.render(g); } if (follower!=null){ follower.render(g); follower.draw(g); } for (int i=0; i<actors.size(); i++){ Actor actor = actors.get(i); if (actor!=follower&&getVisibleRect().intersects(actor.getBounds())){ g.drawImage(actor.getAnimation().getFrameImage(), actor.x - OffSetX, actor.y - OffSetY, null); actor.draw(g); } } } /** * This method returns the visible rectangle * @return The visible rectangle */ public Rectangle getVisibleRect(){ return new Rectangle(OffSetX, OffSetY, global.WIDTH, global.HEIGHT); } @Override public void update(){ if (follower!=null){ if (scrollHorizontally){ OffSetX = global.WIDTH/2 - Math.round((float)follower.x) - tileSize; OffSetX = Math.min(OffSetX, 0); OffSetX = Math.max(OffSetX, global.WIDTH - mapWidth); } if (scrollVertically){ OffSetY = global.HEIGHT/2 - Math.round((float)follower.y) - tileSize; OffSetY = Math.min(OffSetY, 0); OffSetY = Math.max(OffSetY, global.HEIGHT - mapHeight); } } for (int i=0; i<actors.size(); i++){ Actor actor1 = actors.get(i); if (getVisibleRect().contains(actor1.x, actor1.y)){ actor1.update(); for (int j=0; j<actors.size(); j++){ Actor actor2 = actors.get(j); if (actor1.isCollidingWith(actor2)){ actor1.collision(actor2); actor2.collision(actor1); } } } } } but the problem is that all the actors are working, but it just won't scroll. Help Please.. Thanks in Advance.

    Read the article

  • Jump and run HTML5 Game Framework

    - by user1818924
    We're developing a jump and run game with HTML5 and JavaScript and have to build an own game framework for this. Here we have some difficulties and would like to ask you for some advice: we have a "Stage" object, which represents the root of our game and is a global div-wrapper. The stage can contain multiple "Scenes", which are also div-elements. We would implement a Scene for the playing task, for pause, etc. and switch between them. Each scene can therefore contain multiple "Layers", representing a canvas. These Layer contain "ObjectEntities", which represent images or other shapes like rectangles, etc. Each Objectentity has its own temporaryCanvas, to be able to draw images for one entity, whereas another contains a rectangle. We set an activeScene in our Stage, so when the game is played, just the active scene is drawn. Calling activeScene.draw(), calls all sublayers to draw, which draw their entities (calling drawImage(entity.canvas)). But is this some kind of good practive? Having multiple canvas to draw? Each gameloop every layer-context is cleared and drawn again. E.g. we just have a still Background-Layer, … wouldn't it be more useful to draw this once and not to clear it everytime and redraw it? Or should we use a global canvas for example in the Stage and just use this canvas to draw? But we thought this would be to expensive... Other question: Do you have any advice how we could dive into implementing an own framework? Most stuff we find online relies on existing frameworks or they just implement their game without building a framework.

    Read the article

  • java gui changing picture causes heapspace error

    - by pie154
    I have a java programme than when a button is clicked it updates the image on screen to the according image. this will work for the first 15 or so clicks then it causes a java heapspace error. I think it is because of the way I am updating the jpanel that contains the bufferedimage but not sure what the reason is. My code to get make the JPanel contain the new image is, public class extraScreenPanel { static JPanel screenPanel = new JPanel(new BorderLayout()); public static JPanel extraScreenPanel(int dispNum) { JLabel label = new JLabel("" + dispNum + ""); label.setPreferredSize(new Dimension(800, 600)); //label.setUI( new VerticalLabelUI(true) ); label.setVerticalAlignment( SwingConstants.TOP ); screenPanel = imgDisp(dispNum); label.setForeground(Color.white); label.setFont(new Font("Serif", Font.BOLD, 200)); screenPanel.add(label, BorderLayout.PAGE_END ); return screenPanel; } public static JPanel imgDisp(int picNum) { /* String url[] = new String[5000]; String part1; url[0] = "C:/PiPhotoPic/pic16.jpg"; for(Integer i=1;i<5000;i++){ if(i<10){part1 = "C:/temp/new0000000";} else if(i<100){part1 = "C:/temp/new000000";} else if(i<1000){part1 = "C:/temp/new00000";} else {part1 = "C:/temp/new00000";} String num = Integer.toString(i); url[i]= part1 + num + ".jpg"; } if(picNum<0){picNum=0;} String ref = url[picNum];*/ //this code is just to get specific ref for image location BufferedImage loadImg = loadImage(ref); JImagePanel panel = new JImagePanel(loadImg, 0, 0); panel.setPreferredSize(new Dimension(800, 600)); return panel; } public static class JImagePanel extends JPanel{ private BufferedImage image; int x, y; public JImagePanel(BufferedImage image, int x, int y) { super(); this.image = image; this.x = x; this.y = y; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, x, y, null); } } public static BufferedImage loadImage(String ref) { BufferedImage bimg = null; try { bimg = javax.imageio.ImageIO.read(new File(ref)); } catch (Exception e) { e.printStackTrace(); } BufferedImage bimg2 = resize(bimg,800,600); return bimg2; } public static BufferedImage resize(BufferedImage img, int newW, int newH) { int w = img.getWidth(); int h = img.getHeight(); BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType()); Graphics2D g = dimg.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null); g.dispose(); return dimg; } } And the code that updates my gui is, it works by removing the panel from its containg panel and then readding it to it. picPanel = imgDisp.imgDisp(num); repaintPicPanel(); public static void repaintPicPanel() { picPanel.removeAll(); menuPanel.remove(picPanel);; menuPanel.add(picPanel, BorderLayout.LINE_START); }

    Read the article

  • Is using multiple canvas objects a good practice?

    - by user1818924
    We're developing a jump and run game with HTML5 and JavaScript and have to build an own game framework for this. Here we have some difficulties and would like to ask you for some advice: We have a "Stage" object, which represents the root of our game and is a global div-wrapper. The stage can contain multiple "Scenes", which are also div-elements. We would implement a Scene for the playing task, for pause, etc. and switch between them. Each scene can therefore contain multiple "Layers", representing a canvas. These Layer contain "ObjectEntities", which represent images or other shapes like rectangles, etc. Each Objectentity has its own temporaryCanvas, to be able to draw images for one entity, whereas another contains a rectangle. We set an activeScene in our Stage, so when the game is played, just the active scene is drawn. Calling activeScene.draw(), calls all sublayers to draw, which draw their entities (calling drawImage(entity.canvas)). But is this some kind of good practice? Having multiple canvas to draw? Each game loop every layer-context is cleared and drawn again. E.g. we just have a still Background-Layer, … wouldn't it be more useful to draw this once and not to clear it every time and redraw it? Or should we use a global canvas for example in the Stage and just use this canvas to draw? But we thought this would be to expensive...

    Read the article

  • How to shift a vector based on the rotation of another vector?

    - by bpierre
    I’m learning 2D programming, so excuse my approximations, and please, don’t hesitate to correct me. I am just trying to fire a bullet from a player. I’m using HTML canvas (top left origin). Here is a representation of my problem: The black vector represent the position of the player (the grey square). The green vector represent its direction. The red disc represents the target. The red vector represents the direction of a bullet, which will move in the direction of the target (red and dotted line). The blue cross represents the point from where I really want to fire the bullet (and the blue and dotted line represents its movement). This is how I draw the player (this is the player object. Position, direction and dimensions are 2D vectors): ctx.save(); ctx.translate(this.position.x, this.position.y); ctx.rotate(this.direction.getAngle()); ctx.drawImage(this.image, Math.round(-this.dimensions.x/2), Math.round(-this.dimensions.y/2), this.dimensions.x, this.dimensions.y); ctx.restore(); This is how I instanciate a new bullet: var bulletPosition = playerPosition.clone(); // Copy of the player position var bulletDirection = Vector2D.substract(targetPosition, playerPosition).normalize(); // Difference between the player and the target, normalized new Bullet(bulletPosition, bulletDirection); This is how I move the bullet (this is the bullet object): var speed = 5; this.position.add(Vector2D.multiply(this.direction, speed)); And this is how I draw the bullet (this is the bullet object): ctx.save(); ctx.translate(this.position.x, this.position.y); ctx.rotate(this.direction.getAngle()); ctx.fillRect(0, 0, 3, 3); ctx.restore(); How can I change the direction and position vectors of the bullet to ensure it is on the blue dotted line? I think I should represent the shift with a vector, but I can’t see how to use it.

    Read the article

  • Rotating a NetBeans Visual Library Widget

    - by Geertjan
    Trying to create a widget which, when clicked, rotates slightly further on each subsequent click: Above, the bird where the mouse is visible has been clicked a few times and so has rotated a bit further on each click. The code isn't quite right yet and I'm hoping someone will take this code, try it out, and help with a nice solution! public class BirdScene extends Scene {     public BirdScene() {         addChild(new LayerWidget(this));         getActions().addAction(ActionFactory.createAcceptAction(new AcceptProvider() {             public ConnectorState isAcceptable(Widget widget, Point point, Transferable transferable) {                 Image dragImage = getImageFromTransferable(transferable);                 if (dragImage != null) {                     JComponent view = getView();                     Graphics2D g2 = (Graphics2D) view.getGraphics();                     Rectangle visRect = view.getVisibleRect();                     view.paintImmediately(visRect.x, visRect.y, visRect.width, visRect.height);                     g2.drawImage(dragImage,                             AffineTransform.getTranslateInstance(point.getLocation().getX(),                             point.getLocation().getY()),                             null);                     return ConnectorState.ACCEPT;                 } else {                     return ConnectorState.REJECT;                 }             }             public void accept(Widget widget, final Point point, Transferable transferable) {                 addChild(new BirdWidget(getScene(), getImageFromTransferable(transferable), point));             }         }));     }     private Image getImageFromTransferable(Transferable transferable) {         Object o = null;         try {             o = transferable.getTransferData(DataFlavor.imageFlavor);         } catch (IOException ex) {         } catch (UnsupportedFlavorException ex) {         }         return o instanceof Image ? (Image) o : null;     }     private class BirdWidget extends IconNodeWidget {         private int theta = 0;         public BirdWidget(Scene scene, Image imageFromTransferable, Point point) {             super(scene);             setImage(imageFromTransferable);             setPreferredLocation(point);             setCheckClipping(true);             getActions().addAction(ActionFactory.createMoveAction());             getActions().addAction(ActionFactory.createSelectAction(new SelectProvider() {                 public boolean isAimingAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public boolean isSelectionAllowed(Widget widget, Point localLocation, boolean invertSelection) {                     return true;                 }                 public void select(final Widget widget, Point localLocation, boolean invertSelection) {                     theta = (theta + 100) % 360;                     repaint();                     getScene().validate();                 }             }));         }         @Override         public void paintWidget() {             final Image image = getImageWidget().getImage();             Graphics2D g = getGraphics();             g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             Rectangle bounds = getClientArea();             AffineTransform newXform = g.getTransform();             int xRot = image.getWidth(null) / 2;             int yRot = image.getWidth(null) / 2;             newXform.rotate(theta * Math.PI / 180, xRot, yRot);             g.setTransform(newXform);             g.drawImage(image, bounds.x, bounds.y, null);         }     } } The problem relates to refreshing the scene after the rotation. But it would help if someone would just take the code above, add it to their own application, try it out, see the problem for yourself, and develop it a bit further!

    Read the article

  • Smooth drag scrolling of an Isometric map - Html5

    - by user881920
    I have implemented a basic Isometric tile engine that can be explored by dragging the map with the mouse. Please see the fiddle below and drag away: http://jsfiddle.net/kHydg/14/ The code broken down is (CoffeeScript): The draw function draw = -> requestAnimFrame draw canvas.width = canvas.width for row in [0..width] for col in [0..height] xpos = (row - col) * tileHeight + width xpos += (canvas.width / 2) - (tileWidth / 2) + scrollPosition.x ypos = (row + col) * (tileHeight / 2) + height + scrollPosition.y context.drawImage(defaultTile, Math.round(xpos), Math.round(ypos), tileWidth, tileHeight) Mouse drag-scrolling control scrollPosition = x: 0 y: 0 dragHelper = active: false x: 0 y: 0 window.addEventListener 'mousedown', (e) => handleMouseDown(e) , false window.addEventListener 'mousemove', (e) => handleDrag(e) , false window.addEventListener 'mouseup', (e) => handleMouseUp(e) , false handleDrag = (e) => e.preventDefault() if dragHelper.active x = e.clientX y = e.clientY scrollPosition.x -= Math.round((dragHelper.x - x) / 28) scrollPosition.y -= Math.round((dragHelper.y - y) / 28) handleMouseUp = (e) => e.preventDefault() dragHelper.active = false handleMouseDown = (e) => e.preventDefault() x = e.clientX y = e.clientY dragHelper.active = true dragHelper.x = x dragHelper.y = y The Problem As you can see from the fiddle the dragging action is ok but not perfect. How would I change the code to make the dragging action more smooth? What I would like is the point of the map you click on to stay under the mouse point whilst you drag; the same as they have done here: http://craftyjs.com/demos/isometric/

    Read the article

  • Recreating Doodle Jump in Canvas - Platforms spawning out of reach

    - by kushsolitary
    I have started to recreate Doodle Jump in HTML using Canvas. Here's my current progress. As you can see, if you play it for a few seconds, some platforms will be out of the player's reach. I don't know why is this happening. Here's the code which is responsible for the re-spawning of platforms. //Movement of player affected by gravity if(player.y > (height / 2) - (player.height / 2)) { player.y += player.vy; player.vy += gravity; } else { for(var i = 0; i < platforms.length; i++) { var p = platforms[i]; if(player.vy < 0) { p.y -= player.vy; player.vy += 0.08; } if(p.y > height) { position = 0; var h = p.y; platforms[i] = new Platform(); } if(player.vy >= 0) { player.y += player.vy; player.vy += gravity; } } } Also, here's the platform class. //Platform class function Platform(y) { this.image = new Image(); this.image.src = platformImg; this.width = 105; this.height = 25; this.x = Math.random() * (width - this.width); this.y = y || position; position += height / platformCount; //Function to draw it this.draw = function() { try { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } catch(e) {} }; } You can also see the whole code on the link I provided. Also, when a platform goes out of the view port, the jump animation becomes quirky. I am still trying to find out what's causing this but can't find any solution.

    Read the article

  • Drawing visible tiles - side scrolling

    - by Troubleshoot
    Currently I'm calling drawMap every time repaint is called. This is the code I've written for my drawMap method so far. public void drawMap(Graphics2D g2d) { float cameraX = Player.getX() - (Frame.CANVAS_WIDTH / 2); float cameraY = Player.getY() - (Frame.CANVAS_HEIGHT / 2); int tileX = (int) cameraX; int tileY = (int) cameraY; int xIndent = 0, yIndent = 0; int a = 0, b = 0; while (tileX % TILE_SIZE != 0) { tileX--; xIndent++; } while (tileY % TILE_SIZE != 0) { tileY--; yIndent++; } for (int y = tileY; y < tileY + Frame.CANVAS_HEIGHT; y += Map.TILE_SIZE) { for (int x = tileX; x < tileX + Frame.CANVAS_WIDTH; x += Map.TILE_SIZE) { if ((y / TILE_SIZE < 0 || x / TILE_SIZE < 0) || (y / TILE_SIZE > columnSize)) break; g2d.drawImage(map[y / TILE_SIZE][x / TILE_SIZE], a - xIndent, b - yIndent, null); a += TILE_SIZE; } a = 0; b += TILE_SIZE; } } The idea behind this is that it gets the camera position and draws the map relative to the player position. However, instead of the player being in the center of the screen all the time, the player actually moves away from the center as it scrolls to the right, and moves towards to center as it scrolls to the left. I've been trying to pinpoint what I've done wrong but I can't seem to find it. My code also seems quite messy, so am I doing this the correct way?

    Read the article

  • background in JAVA [closed]

    - by leen.zd
    how can i put a background image in my java code? this is my code... what's error? import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class background extends JFrame { private Container c; private JPanel imagePanel; public background() { initialize(); } private void initialize() { setDefaultCloseOperation(EXIT_ON_CLOSE); c = getContentPane(); imagePanel = new JPanel() { public void paint(Graphics g) { try { BufferedImage image = ImageIO.read(new File("http://www.signe-zodiaque.com/images/signes/balance.jpg")); g.drawImage(image, 1000, 2000, null); } catch (IOException e) { e.printStackTrace(); } } }; imagePanel.setPreferredSize(new Dimension(640, 480)); c.add(imagePanel); }

    Read the article

  • using NetBeans for rotate a figure in a label [migrated]

    - by user134812
    I was reading this post: http://forums.netbeans.org/post-8864.html and what I have done so far is to make a jFrame in NetBeans, on it I have drawn a jPanel and inisde the panel I have drawn a jLabel on it and use the icon property to put an image on it; until now all is so far so good. I would like to make a program that everytime I click on the figure it rotates it to the right. Actually I have found the following code: public class RotateImage extends JPanel{ // Declare an Image object for us to use. Image image; // Create a constructor method public RotateImage(){ super(); // Load an image to play with. image = Toolkit.getDefaultToolkit().getImage("Duke_Blocks.gif"); } public void paintComponent(Graphics g){ Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g. g2d.translate(170, 0); // Translate the center of our coordinates. g2d.rotate(1); // Rotate the image by 1 radian. g2d.drawImage(image, 0, 0, 200, 200, this); } but for what I see this code is for making the panel and other components from scratch, for my purposes it is not so good because I need to put several figures on my jFrame. Could somebody can give me a hint how to do this?

    Read the article

  • output image is not displayed

    - by gerry chocolatos
    so, im doing an image detection which i have to process on each red, green, n blue element to get the edge map and combine them become one to show the output. but it doesnt show my output image would anyone pls be kind enough to help me? here is my code so far. //get the red element process_red = new int[width * height]; counter = 0; for(int i = 0; i < 256; i++) { for(int j = 0; j < 256; j++) { int clr = buff_red.getRGB(j, i); int red = (clr & 0x00ff0000) >> 16; red = (0xFF<<24)|(red<<16)|(red<<8)|red; process_red[counter] = red; counter++; } } //set threshold value for red element int threshold = 100; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int bin = (buff_red.getRGB(x, y) & 0x000000ff); if (bin < threshold) bin = 0; else bin = 255; buff_red.setRGB(x,y, 0xff000000 | bin << 16 | bin << 8 | bin); } } and i do the same way for my green n blue elements. and then i wanted to get to combination of the three by doing it this way: //combine the three elements process_combine = new int[width * height]; counter = 0; for(int i = 0; i < 256; i++) { for(int j = 0; j < 256; j++) { int clr_a = buff_red.getRGB(j, i); int ar = clr_a & 0x000000ff; int clr_b = buff_green.getRGB(j, i); int bg = clr_b & 0x000000ff; int clr_c = buff_blue.getRGB(j, i); int cb = clr_b & 0x000000ff; int alpha = 0xff000000; int combine = alpha|(ar<<16)|(bg<<8)|cb; process_combine[counter] = combine; counter++; } } buff_rgb = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB); Graphics rgb; rgb = buff_rgb.getGraphics(); rgb.drawImage(output_rgb, 0, 0, null); rgb.dispose(); repaint(); and to show the output whic is from the combining process, i use a draw method: g.drawImage(buff_rgb,800,100,this); but still it doesnt show the image. can anyone pls help me? ur help is really appreciated. thanks.

    Read the article

  • Java Animation Memory Overload [on hold]

    - by user2425429
    I need a way to reduce the memory usage of these programs while keeping the functionality. Every time I add 50 milliseconds or so to the set&display loop in AnimationTest1, it throws an out of memory error. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; //set&display loop while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Animation Color [on hold]

    - by user2425429
    I'm having problems in my java program for animation. I'm trying to draw a hexagon with a shape similar to that of a trapezoid. Then, I'm making it move to the right for a certain amount of time (DEMO_TIME). Animation and ScreenManager are "API" classes, and AnimationTest1 is a demo. In my test program, it runs with a black screen and white stroke color. I'd like to know why this happened and how to fix it. I'm a beginner, so I apologize for this question being stupid to all you game programmers. Here is the code I have now: import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.ImageIcon; public class AnimationTest1 { public static void main(String args[]) { AnimationTest1 test = new AnimationTest1(); test.run(); } private static final DisplayMode POSSIBLE_MODES[] = { new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(640, 480, 32, 0), new DisplayMode(640, 480, 24, 0), new DisplayMode(640, 480, 16, 0) }; private static final long DEMO_TIME = 4000; private ScreenManager screen; private Image bgImage; private Animation anim; public void loadImages() { // create animation List<Polygon> polygons=new ArrayList(); int[] x=new int[]{20,4,4,20,40,56,56,40}; int[] y=new int[]{20,32,40,44,44,40,32,20}; polygons.add(new Polygon(x,y,8)); anim = new Animation(); //# of frames long startTime = System.currentTimeMillis(); long currTimer = startTime; long elapsedTime = 0; boolean animated = false; Graphics2D g = screen.getGraphics(); int width=200; int height=200; while (currTimer - startTime < DEMO_TIME*2) { //draw the polygons if(!animated){ for(int j=0; j<polygons.size();j++){ for(int pos=0; pos<polygons.get(j).npoints; pos++){ polygons.get(j).xpoints[pos]+=1; } } anim.setNewPolyFrame(polygons , width , height , 64); } else{ // update animation anim.update(elapsedTime); draw(g); g.dispose(); screen.update(); try{ Thread.sleep(20); } catch(InterruptedException ie){} } if(currTimer - startTime == DEMO_TIME) animated=true; elapsedTime = System.currentTimeMillis() - currTimer; currTimer += elapsedTime; } } public void run() { screen = new ScreenManager(); try { DisplayMode displayMode = screen.findFirstCompatibleMode(POSSIBLE_MODES); screen.setFullScreen(displayMode); loadImages(); } finally { screen.restoreScreen(); } } public void draw(Graphics g) { // draw background g.drawImage(bgImage, 0, 0, null); // draw image g.drawImage(anim.getImage(), 0, 0, null); } } ScreenManager: import java.awt.Color; import java.awt.DisplayMode; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class ScreenManager extends JPanel { private GraphicsDevice device; /** Creates a new ScreenManager object. */ public ScreenManager() { GraphicsEnvironment environment=GraphicsEnvironment.getLocalGraphicsEnvironment(); device = environment.getDefaultScreenDevice(); setBackground(Color.white); } /** Returns a list of compatible display modes for the default device on the system. */ public DisplayMode[] getCompatibleDisplayModes() { return device.getDisplayModes(); } /** Returns the first compatible mode in a list of modes. Returns null if no modes are compatible. */ public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; } /** Returns the current display mode. */ public DisplayMode getCurrentDisplayMode() { return device.getDisplayMode(); } /** Determines if two display modes "match". Two display modes match if they have the same resolution, bit depth, and refresh rate. The bit depth is ignored if one of the modes has a bit depth of DisplayMode.BIT_DEPTH_MULTI. Likewise, the refresh rate is ignored if one of the modes has a refresh rate of DisplayMode.REFRESH_RATE_UNKNOWN. */ public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; } /** Enters full screen mode and changes the display mode. If the specified display mode is null or not compatible with this device, or if the display mode cannot be changed on this system, the current display mode is used. <p> The display uses a BufferStrategy with 2 buffers. */ public void setFullScreen(DisplayMode displayMode) { JFrame frame = new JFrame(); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(true); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } } frame.createBufferStrategy(2); Graphics g=frame.getGraphics(); g.setColor(Color.white); g.drawRect(0, 0, frame.WIDTH, frame.HEIGHT); frame.paintAll(g); g.setColor(Color.black); g.dispose(); } /** Gets the graphics context for the display. The ScreenManager uses double buffering, so applications must call update() to show any graphics drawn. <p> The application must dispose of the graphics object. */ public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } } /** Updates the display. */ public void update() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); if (!strategy.contentsLost()) { strategy.show(); } } // Sync the display on some systems. // (on Linux, this fixes event queue problems) Toolkit.getDefaultToolkit().sync(); } /** Returns the window currently used in full screen mode. Returns null if the device is not in full screen mode. */ public Window getFullScreenWindow() { return device.getFullScreenWindow(); } /** Returns the width of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } } /** Returns the height of the window currently used in full screen mode. Returns 0 if the device is not in full screen mode. */ public int getHeight() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getHeight(); } else { return 0; } } /** Restores the screen's display mode. */ public void restoreScreen() { Window window = device.getFullScreenWindow(); if (window != null) { window.dispose(); } device.setFullScreenWindow(null); } /** Creates an image compatible with the current display. */ public BufferedImage createCompatibleImage(int w, int h, int transparency) { Window window = device.getFullScreenWindow(); if (window != null) { GraphicsConfiguration gc = window.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, transparency); } return null; } } Animation: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Polygon; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private ArrayList frames; private int currFrameIndex; private long animTime; private long totalDuration; /** Creates a new, empty Animation. */ public Animation() { frames = new ArrayList(); totalDuration = 0; start(); } /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(BufferedImage image, long duration){ ScreenManager s = new ScreenManager(); totalDuration += duration; frames.add(new AnimFrame(image, totalDuration)); } /** Starts the animation over from the beginning. */ public synchronized void start() { animTime = 0; currFrameIndex = 0; } /** Updates the animation's current image (frame), if necessary. */ public synchronized void update(long elapsedTime) { if (frames.size() >= 1) { animTime += elapsedTime; /*if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; }*/ while (animTime > getFrame(0).endTime) { frames.remove(0); } } } /** Gets the Animation's current image. Returns null if this animation has no images. */ public synchronized Image getImage() { if (frames.size() > 0&&!(currFrameIndex>=frames.size())) { return getFrame(currFrameIndex).image; } else{ System.out.println("There are no frames!"); System.exit(0); } return null; } private AnimFrame getFrame(int i) { return (AnimFrame)frames.get(i); } private class AnimFrame { Image image; long endTime; public AnimFrame(Image image, long endTime) { this.image = image; this.endTime = endTime; } } public void setNewPolyFrame(List<Polygon> polys,int imagewidth,int imageheight,int time){ BufferedImage image=new BufferedImage(imagewidth, imageheight, 1); Graphics g=image.getGraphics(); for(int i=0;i<polys.size();i++){ g.drawPolygon(polys.get(i)); } addFrame(image,time); g.dispose(); } }

    Read the article

  • Crop and Resize Image to Specific Dimensions

    - by Crunchy
    I need some help cropping and resizing images using CSharp.net. My goal here is to take an image and reduce it to 50px by 50px. The following code I found here will do that, however it's scaling the image as well. Ideally I want to scale the image down to as close to 50px by 50px as possible and then remove the parts of the image that are outside 50px by 50px. public Image ResizeImage(Image img, int width, int height) { Bitmap b = new Bitmap(width, height); using (Graphics g = Graphics.FromImage((Image)b)) { g.DrawImage(img, 0, 0, width, height); } return (Image)b; }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >