22samurai22
Ex Member
Re: Drag and drop text - attach text to object/sha
Reply #2 - Oct 21st , 2005, 5:33am
The solution above is a reasonable offhand approach, but doesn't address the critical issue for dragging - knowing how much space the text takes up on the screen. In fact, There is not an easy, built in way to find out the 'rect' that contains the text. If there was, a simple intersection test could be performed with the mouseX and mouseY and see if it was inside or outside a particular boundary. Suggestions: -use textWidth(), textAscent(), and textDescent to determine the text boundaries. (this is probably easiest with textAlign(LEFT), but, with a bit more calculation, it would be possible to do with textAlign(CENTER) or RIGHT). NOTE: this doesn't work if your text is more than one line. Consider this example: (taken from the example in the documentation) <code> PFont font; font = loadFont("FFScala-32.vlw"); textFont(font, 32); //this one works fine String s1 = "Tokyo"; float s1w = textWidth(s1); text(s1, 0, 40); line(s1w, 0, s1w, 50); //this one breaks String s = "Tokyo\nTokyo is big"; float sw = textWidth(s); text(s, 0, 85); stroke(255); line(sw, 50, sw, 100); </code> Ideally, the textWidth() method should take the '\n' character into consideration, as well as have a sister method called textHeight(), which would take the '\n''s into account as well. -There is also a nice text command that encloses the text in a box and does word-wrapping: <code> PFont font; font = loadFont("FFScala-Bold-12.vlw"); textFont(font, 12); String s = "The quick brown fox jumped over the lazy dog."; text(s, 15, 20, 70, 70); </code> However, this one doesn't work so well if you have strings that change for some reason, so you don't know the height/width at all and you can't pre-define a rectangular boundary. Sometimes you want to discover that boundary instead of defining it. -(for anyone) Add a calculation method that takes 'rect'-style boundaries and an x,y coordinate, and returns true if the coords are in-bounds and false if not <code> boolean isInside(int x,int y, int width, int height, int xcoord, int ycoord) { if ((xcoord>=x)&&(xcoord<=x+width) &&(ycoord>=y)&&(ycoord<=y+height)) { return true } else {return false;} } </code> Then you could use it like this: <code> color col=color(FF99CC); void draw() { fill(col); rect(10,10,100,50); } void mousePressed() { // if the click happened inside the space if isInside(10,10,100,50,mouseX,mouseY) { col=(random(255),random(255),random(255) } } </code> This code will make a kind of button you can click on. See the above for how to make it drag around. -22