Negative Number in fillRect()
I am using a negative number to have fillRect()
go the opposite way. It works well on my c开发者_JAVA百科omputer, but my friends cannot see it working properly. What do I do?
page.fillRect (12, 12, -5, 10);
There are two schools of thought on this.
One is that any polygon with a negative dimension is nonsensical and should not be rendered - what do you mean it's -10 pixels wide??
The other is that a negative dimension simply inverts the polygon on that dimension's axis.
Most painting systems apply the latter logic. My experience in painting with Java has always been this, though I would not often have had negative dimensions, so my experience might not count for much.
As to what you can do:
- You might need to have your friend update his Java version.
- Otherwise you must perform the inversion yourself, by checking for a negative dimension and transposing your x,y origin in order to make the dimension positive. That is, the rectangle [10,10,-5,5] is spatially equivalent to [5,10,5,5]. The negative dimension is added to the origin coordinate, and then made absolute. Note, this can result in a negative origin, but hopefully the drawing system is not quite that messed up.
Personally, I would prefer to require a newer JVM, if possible.
Otherwise my recommended code would be:
public void fillRect(Graphics gc, int x, int y, int width, int height) {
if(width <0) { x+=width; width =-width; }
if(height<0) { x+=height; height=-height; }
gc.fillRect(x,y,width,height);
}
Also, note that you'll need similar for other drawing operations.
Lastly, I would be suspicious of another mistake in all this, since the behavior is very surprising - I would simplify everything down to a minimal test program, with debug output and verify before wrapping a crap load of painting primitives.
My guess is that you and your freind are using 2 different versions of Java. your supports fillrect with a negative value and your freind's doesn't. (or even sdk vs jre).
what that shows is that you should write this a different way to have your applet run on all versions.
why not simply move your x of -5 ?
if you want to do it in a more neat way
public void myfillRect(graphics page, int x, int y, int width, int height){
if(width <0)
x-=Math.abs(width);
if(height <0)
y-=Math.abs(height);
page.rectfill(x,y,Math.abs(width), Math.abs(height));
}
Just indicating a small issue in Lawrence code that appear when you drag up the rect which give wrong height value.
The problem is in the row
if(height<0) { x+=height; height=-height; }
and it has to be y not x
if(height<0) { y+=height; height=-height; }
in total:
public void fillRect(Graphics gc, int x, int y, int width, int height) {
if(width <0) { x+=width; width =-width; }
if(height<0) { y+=height; height=-height; }
gc.fillRect(x,y,width,height);
}
精彩评论