How to draw a new background picture automatically with the code -- Greenfoot tutorial
Find other posts in the same category: | | |

Long description

Michael Kolling made 4 Greenfoot video tutorials about how to create a background.

Here is the page that lists all the official Greenfoot video tutorials
http://greenfoot.org/doc/videos.html

Scroll down to the part called "Making Backgrounds"

Part 1 is actually a Photoshop tutorial that is not related to Greenfoot
http://greenfoot.org/videos/making-backgrounds-part1.mov

Part 2 tells you how to use the "Browse for more images" button to import an image you made in Photoshop.
http://greenfoot.org/videos/making-backgrounds-part2.mov

Part 3 explains that images are tiled. This means if an image is one-fourth the size of your world, then the image will appear 4 times in your world.
http://greenfoot.org/videos/making-backgrounds-part3.mov

Part 4 is the important one. It teaches you how to write code to paint a background image.
http://greenfoot.org/videos/making-backgrounds-part4.mov

On the Greenfoot website, the source code is mislabeled. (Today is Dec. 18, 2008). The source code for part 4 is available, but it is marked as source code for part 3.

Here is the code for the World sub-class MyWorld. It creates a world that looks like space, with 300 stars. Here are the main steps: choose the color to be black, filling the background with color, draw 300 white ovals.

import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Color;

/**
* Write a description of class MyWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MyWorld extends World
{

/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld()
{
super(500, 350, 1);
GreenfootImage bg = getBackground();
bg.setColor(Color.BLACK);
bg.fill();
createStars(300);
}

private void createStars(int numberOfStars)
{
GreenfootImage bg = getBackground();
bg.setColor(Color.GRAY);
for (int i = 0; i < numberOfStars; i++) {
int x = Greenfoot.getRandomNumber( getWidth() );
int y = Greenfoot.getRandomNumber( getHeight() );
bg.fillOval(x, y, 1, 1);
}
}


}


To see articles on the same topic, click the links below the name of the author at the top of this page.