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

2022/2/13

Problem with setImage text style

Roshan123 Roshan123

2022/2/13

#
My attempt: setImage(new GreenfootImage("I am an alien \nwill you talk with me?", 30, new Color(0,0,0), new Color(0,0,0,0))); How it looks: I am an alien Will you talk with me? How I want: I am an alien Will you talk with me? Plz help me to solve this problem
danpost danpost

2022/2/13

#
Create each line individually. Draw them onto a new image that is twice the height and with a width of the longer line. Then, set that image to the actor.
Roshan123 Roshan123

2022/2/13

#
Is their any other way to show the text? I will be adding such type of new-new sentences again and again which will be a time taking task for me
danpost danpost

2022/2/13

#
Create a new method that will take a list of lines, the font size and the two colors and return the combined image. It can then be used for any multi-line set of text. So, instead of calling "new GreenfootImage(String, int, Color, Color)" directly, you can call this new method which will call it multiple times -- once for each line.
danpost danpost

2022/2/13

#
It might look something line this for what you have above:
String[] lines = { "I am an alien", "Will you talk with me?" }; // the lines to put onto one image
setImage(multiLineImage(lines, 30, Color.BLACK, new Color(0, 0, 0, 0))); // setting needed image to actor
using this method:
private GreenfootImage multiLineImage(String[] lines, int fontSize, Color textColor, Color backgroundColor)
{
    int lineCount = lines.length; // number of lines
    GreenfootImage[] lineImages = new GreenfootImage[lineCount]; // array for images of each line
    int maxWidth = 0; // to track widest line created
    for (int i=0; i<lineCount; i++) // for each line to create
    {
        lineImages[i] = new GreenfootImage(lines[i], fontSize, textColor, backgroundColor); // create line
        if (lineImage[i].getWidth() > maxWidth) maxWidth = lineImage[i].getWidth(); // record if widest, so far
    }
    int lineHeight = lines[0].getHeight(); // height of a line
    GreenfootImage img = new GreenfootImage(maxWidth, lineCount*lineHeight); // create blank image (full-sized)
    for (int i=0; i<lineCount; i++) // for each line
    {
        img.drawImage(lines[i], 0, lineHeight*i); // draw line onto full-sized image
    }
    return img; // return full-sized image with all lines drawn onto it
}
Roshan123 Roshan123

2022/2/16

#
Got it! Thanks
You need to login to post a reply.