This site requires JavaScript, please enable it in your browser!
Greenfoot back
keizerbob
keizerbob wrote ...

2016/2/12

How-To: draw directly on background/image?

keizerbob keizerbob

2016/2/12

#
I'm moving to Greenfoot from using Processing (another Java-based tool for students, artists, etc.). Although the online tutorials and the 2nd ed. book are great, I thought I'd try translating a small Processing project into Greenfoot world. First problem right at the beginning was not understanding how to draw simple figures using low-level GreenfootImage commands. I'd like to do something like this: 1. Create transparent image 2. Draw colored rectangle that fills the space 3. Draw basic figures using drawRect(...) Perhaps I'm still mentally stuck in "Processing World" but, at this point, I'm curious about drawing basic figures directly rather than importing PNG-format images.
danpost danpost

2016/2/12

#
In greenfoot, (1) is as simple as using the 'GreenfootImage(int width, int height)' constructor. A transparent image of size (200, 100) is created with:
1
GreenfootImage image = new GreenfootImage(200, 100);
Now (2) is just as easy -- the 'fill' method of the GreenfootImage class allows you to fill the space:
1
2
// working on 'image' just created above
image.fill();
The image will fill with the color black as it is the default drawing color for new GreenfootImage objects. You can change the drawing color prior to filling it with the 'setColor' method of the GreenfootImage class:
1
image.setColor(java.awt.Color.BLUE);
All future drawing methods will use that color until that setting for that image is changed. Your last item (3), using 'drawRect(int x, int y, int right, int down)' will use the current drawing color of the image to draw a rectangle, starting at the point (x, y) on the image (where (0, 0) is the top-left corner of the image) and going across to the right and down. If 'x+right >= width' or 'y+down >= height', then some of the rectangle drawn will not appear on the image (same goes if 'x < 0' or 'y < 0'). Now, I just noticed in the title that you wanted to draw on the background image. The World class method 'getBackground' can be used to gain a reference to the background image:
1
2
// in World subclass
GreenfootImage bg = getBackground();
Then you can modify the image by applying the GreenfootImage methods to 'bg'. A reference to an image of an Actor object can be gotten with:
1
2
// in an Actor subclass
GreenfootImage image = getImage();
You will find the 'getBackground' method in the World class API and the 'getImage' method in the Actor class API (as well as a 'set' method for both in both places).
keizerbob keizerbob

2016/2/12

#
danpost: Thanks for exactly the basic info I was after!
You need to login to post a reply.