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

2013/10/18

change color of the last character of a text?

kolozz kolozz

2013/10/18

#
Can anyone help me with this? I have no idea how to use charAt to do this or what the best way to do this is.
Kartoffelbrot Kartoffelbrot

2013/10/18

#
Do you want to make a GreenfootImage with text?
kolozz kolozz

2013/10/18

#
Kartoffelbrot wrote...
Do you want to make a GreenfootImage with text?
Yes, I have done that, but I want to change the color of the last character of the text I have created.
Kartoffelbrot Kartoffelbrot

2013/10/18

#
Make two GreenfootImages and the draw them togethor ontop of one.
int size = 10;
GreenfootImage a = new GreenfootImage("Tes",size,Color.RED,new Color(0,0,0,0));
GreenfootImage b = new GreenfootImage("t",size,Color.BLUE,new Color(0,0,0,0));
GreenfootImage fusion = new GreenfootImage(a.getWidth()+b.getWidth(),size);
fusion.drawImage(a, 0,0);
fusion.drawImage(b,fusion.getWidth()-b.getWidth(),0);
Fusion is the the image you want to have. Please report here, when you have tried it.
Kartoffelbrot Kartoffelbrot

2013/10/18

#
If it works as it should do, you can change the size and the texts to whatever you want.
Gevater_Tod4711 Gevater_Tod4711

2013/10/18

#
@Kartoffelbrot I think it would be better to draw the whole text and overdraw the first letters. So you can be shure that the last letter is at the right position:
int size = 10;  
GreenfootImage a = new GreenfootImage("Tes", size, Color.red, null);  
GreenfootImage b = new GreenfootImage("Test", size, Color.blue, null);
b.drawImage(a, 0, 0);
danpost danpost

2013/10/18

#
The method Kartoffelbrot supplied should work. Although a size of 10 if awfully small. Also 'fusion.getWidth()-b.getWidth()' in the last line can be replaced with 'a.getWidth()'. I was thinking along these lines:
int size = 24;
String text = "Kartoffelbrot";
Color textColor = Color.blue;
Color lastColor = Color.red;
Color transparent = new Color(0, 0, 0, 0);
GreenfootImage image = new GreenfootImage(text, size, lastColor, transparent);
String incomplete = text.substring(0, text.length()-1);
GreenfootImage partial = new GreenfootImage(incomplete, size, textColor, transparent);
image.drawImage(partial, 0, 0);
With this, you are only dealing with two images and you do not have to mess with the widths of them. EDIT: basically what Gevater_Tod4711 suggested (was working on this while his post was being made).
kolozz kolozz

2013/10/20

#
Thanks guys, it works!
bourne bourne

2013/10/20

#
Without relying on tricks, take a look at the FontMetrics class and its charsWidth method. It can be complicated when using several substrings, but works great for broader applications of the problem. Most of my GUI components in my GUI Components scenario use it.
You need to login to post a reply.