[SOLVED] Why Canvas.drawRect() draws filled rect?


(Vampir) #1

Canvas.drawRect() acts exactly as Canvas.fill(). Why? I expected to draw outline rectangle.

var canvas:Canvas = new Canvas(w, h);
var rect:Rectangle = new Rectangle(0, 0, w, h);
canvas.drawRect( rect, 0x00ff00 );

Should I use setPixel method instead?


(Jonathan Stoler) #2

You can use Draw.rectPlus(), which takes a fill boolean argument. Set it to false.


(Vampir) #3

Thank you, it works. But I have to use Draw.rectPlus() at every render event instead of draw once on canvas and use it as graphic… I’m afraid of performance issues.


(Jonathan Stoler) #4

(Note: not able to check this right now but I’m pretty sure it’s right!)

You can use Draw.setTarget() but you’ll need to use BitmapData rather than Canvas. Be sure to call Draw.resetTarget() after you’re done.

You can then create an Image from that BitmapData and add it to your Entity or World.

There are other ways as well. BitmapData has its own way of drawing rectangles that don’t involve the Draw class, for instance.


(Zachary Lewis) #5

I wrote an (untested) function for you to quickly generate rectangles with borders and stuff.

/**
 * Create a rectangle or outlined rectangle.
 * @param	rect The rectangle to create.
 * @param	color The color of the rectangle or border.
 * @param	borderWidth The thickness of the border.
 * @return	The new rectangle.
 */
public function createRectangle(rect:Rectangle, color:uint = 0xffffffff, borderWidth:int = 0):BitmapData
{
	var b:BitmapData = new BitmapData(rect.width, rect.height, true, color);

	if (borderWidth > 0)
	{
		var r:Rectangle = rect.clone();
		r.inflate(-borderWidth);

		b.fillRect(r, 0);
	}

	return b;
}

Here’s how you’d use it.

// Create a 128x256 solid red rectangle Image.
var solid:Image = new Image(createRectangle(new Rectangle(0, 0, 128, 256), 0xff0000));

// Create a 32x48 hollow blue rectangle Stamp with a 2 pixel border.
var outline:Stamp = new Stamp(createRectangle(new Rectangle(0, 0, 32, 48), 0x0000ff, 2));

(Vampir) #6

Thank you, Jonathan and Zachary :slight_smile: This forum is incredibly friendly and helpful. Now I have all the rectangles I wanted!

Here is final code:

private function createRectangle(rect:Rectangle, color:uint = 0xffffffff, borderWidth:int = 0):BitmapData
{
	var b:BitmapData = new BitmapData(rect.width, rect.height, true, color);
	
	if (borderWidth > 0)
	{
		var r:Rectangle = rect.clone();
		r.inflate(-borderWidth, -borderWidth); // the only edit I made is 2nd argument
		
		b.fillRect(r, 0);
	}
	
	return b;
}

And function call:

graphic = new Stamp( createRectangle(rect, 0xffffffff, 1));