3

I am trying to write a watermarking program with java , So I found this piece of code for the same.

I made my own adaptation for my purposes like so (Full src : https://gist.github.com/1373080/)

 /**
 *
 * This method  converts a multiline string into an ArrayList of Strings
 * Each item on the array list is a line of the string.
 * @param str A multiline string
 * @return An ArrayList of strings , a string per line of text
 * @see java.util.ArrayList
 */
private static ArrayList<String> convertStringToLineString(String str){
    ArrayList<String> string = new ArrayList<String>();
    String s = new String ();
    char [] ca = str.toCharArray();

    for(int i=0;i<ca.length;i++){
        if(ca[i] == '\n'){
            string.add(s);
            s = new String();
        }
        s += ca[i];
    }
    return string;
}

The string is drawn like so

    int x =(img.getIconWidth() - (int) rect.getWidth()) / 2,
    y =(img.getIconHeight() - (int) rect.getHeight()) / 2;

    ArrayList<String> watermarks = convertStringToLineString(watermark);
    for (String w : watermarks){
    g2d.drawString(w,x,y);
        y+=20;
    }

The problem I am facing is that a string like a calendar

 November 2011      
Su Mo Tu We Th Fr Sa  
       1  2  3  4  5  
 6  7  8  9 10 11 12  
13 14 15 16 17 18 19  
20 21 22 23 24 25 26  
27 28 29 30   

which contains multiple lines does not get drawn properly .

Example enter image description here

PS: I am open to any type of solution using java, even the ones that use other libraries.

Using the following line works

g2D.setFont(new Font("Monospaced", Font.PLAIN, 12));

But there must be a more elegant solution that works for Any type of font .

Gautam
  • 7,868
  • 12
  • 64
  • 105

2 Answers2

3

I don't really like you method for splitting multiline String. Try this:

public static List<String>  convertStringToLineString(String str) {
    if (str==null)
        return null;

    String[] parts = str.split("\n");
    return Arrays.asList(parts);
}
execc
  • 1,083
  • 12
  • 25
2

The problem is that a space takes less horizontal space than a number in a proportional font. The easiest fix is to use a fixed-width font like this:

g2D.setFont(new Font("Monospaced", Font.PLAIN, 12));

before drawing the text.

Making your own grid for when using a proportional font is also possible without using other libraries, but it is more work.

MartinZ
  • 428
  • 3
  • 3
  • Wow that really worked thanks !! , But there must be a more elegant solution to this . – Gautam Nov 17 '11 at 13:35
  • 2
    With a proportional font this is an inherent problem and cannot be fixed without specifically handling the desired alignment points. – MartinZ Nov 17 '11 at 13:39