Drawing Rectangle images-LibGdx - libgdx

In my first LibGdx Project,I want to draw some rectangles.
I am not looking for shape rendering purpose.I am aiming to implement a function like what fillRect() in j2me do.I have to draw filled rectangles and need to manipulate it(changing size,rotating.. etc).
When I google about it, always getting shapeRenderer related things only.
Please mention how can I draw and manipulate my own images.

Draw Rectangle by using Pixmap.
Texture texture=getPixmapTexture(Color.WHITE);
Sprite sprite=new Sprite(texture); //Used for drawing 2D sprites.
//or
Image image=new Image(texture); //2D scene graph node.
public static Texture getPixmapTexture(Color color){
return new Texture(PixmapBuilder.getPixmapRectangle(1, 1, color));
}
public static Pixmap getPixmapRectangle(int width, int height, Color color){
Pixmap pixmap=new Pixmap(width, height, Pixmap.Format.RGBA8888);
pixmap.setColor(color);
pixmap.fillRectangle(0,0, pixmap.getWidth(), pixmap.getHeight());
return pixmap;
}

The answer by Abhishek is correct.
However, if you have just started game developement with LibGDX, I would check whether you need at all to perform such operation (draw a rectangle).
In libGDX you can use Scene2D which allow you to create a Stage, Actors and direct them on your stage.
So instead of drawing a rectangle, you create an actor, such as an image, to which you can associate a texture, a button or a TextBox and place it on your screen.
Scene2D allows you to then use things like Action or rotation, scaling..
There are some good visual demos about that on Libgdx.info
I am mentioning this because moving to Scene2D later may be more complicated than if you make that decision early on.

Related

Actionscript 3: Drawing lines and bitmaps the right way

I'm just getting started with Flash/ActionScript and it seems to be the general consensus to create Sprites, Bitmaps, MovieClips, etc for various objects in order to represent pictures and other graphics.
However, the way I'm used to writing games and whatnot in other languages is to just loop repeatedly and each frame use something similar to the Graphics object to redraw the scene on the main Sprite. Is this how it's also done in Flash, and is it good practice? I can do it this way, but I'm wondering if there's some Flash ecosystem standard instead.
Here's an example of the way I'm used to:
public class MyApp extends Sprite
{
public function MyApp()
{
var t:Timer = new Timer(20);
t.addEventListener(TimerEvent.TIMER, update);
t.start();
}
public function update(e:TimerEvent)
{
this.graphics.clear();
//Rendering code and updating of objects.
}
}
Is this acceptable?
Well, it depends.
In Flash, you have the option of relying on the Flash Player's vector rasterizer and rendering system, which will figure out all the redrawing for you. For instance, you can draw once to a Sprite then simply apply transforms to the sprite (set x, y, width, height, rotation, scaleX, scaleY, transform.matrix, transform.colorTransform, etc). Any of these objects could be a vector shape or a bitmap, and you can also use cacheAsBitmap and cacheAsBitmapMatrix for even more redraw optimization. The Flash Player will only redraw areas that change, on the frame that they change. I would consider this the traditional "Flash way".
Using the Graphics API is just a programmatic way to create vector shape data. Think of it as a code alternative to drawing in the Flash IDE. You could draw using Graphics once when the object is created, or if you needed to change the actual shape (ie not just the transform) you are correct that you would clear() and redraw it. However, ideally you would not be doing that a lot. If you find yourself redrawing the shape a lot, you might want to move to a pre-rendered sprite-sheet approach. In that case you use BitmapData to more quickly copy pre-drawn pixel data to a Bitmap object. This is generally faster than relying on the vector rasterizer to render your Graphics commands, as long as you use the fast pixel methods like copyPixels(). This is probably closer to the sort of rendering systems you are used to in other platforms that don't have a vector rasterizer built in.
Lastly, it's worth noting that the newest (and fastest) way to render objects in Flash is completely different than all that. It's called Stage3D and it uses a completely different rendering pipeline than the vector rasterizer. It's powered by GPU rendering APIs, so it's blazing fast (great for games) but has no vector rasterizing abilities. It can be used for both 3D and 2D. It's a bit more involved to work with, but there are some useful frameworks to make it easier, most notably the Starling 2D framework.
Hope that helps.
The "Flash way" is to use EnterFrame event instead of using timer to draw. You must make your calculation whenever you want but let flash draw you scene.
It works the same way in actionscript.
public class App extends Sprite // adding "my" to identifier names doesn't add any information, so there's no real point in doing it
{
public function App()
{
addEventListener(Event.ENTER_FRAME, update); // "each frame"
}
private function update(e:Event):void //not just parameters of functions have a type, but also their return value
{
graphics.clear(); // no need for "this" here
//Rendering code and updating of objects.
}
}
Keep in mind that the Graphics API is vector based and as such will only draw so many things before dropping performance.
Sprite is a general purpose container, not to be confused with what the term "sprite" stands for in a sprite sheet.
What you are probably referring to when saying "main Sprite" is some rectangular region of pixels that you can manipulate.In this case, a BitmapData is what you want, which is displayed with a Bitmap object.
BitmapData does not offer a graphics property. Essentially, drawing vectors and manipulating pixels are treated separately in As3. If you want to draw a line in a BitmapData object, you'd have to first draw the line as a vector into a Sprite (or better Shape, if all you want to do is draw on it) using its graphics property, then use draw() of BitmapData to set its pixels according to the drawn line.

Delegate draw function to stage and customize inside actors

I have a question about stages and actors in libgdx. I'd like to delegate the draw function to stage, in order to use actions, but I need to customize these actors. Are there any way to extend an actor, assign him an Image or Texture, and not implement the draw method? Is mandatory implement the draw method or is there a way to delegate this to the stage?
Thanks you!
I think your are looking for Image. Image is a subclass of Actor which allready implements a draw-method itself. You can simply give its constructor a Drawable and it will draw it at the right position with the right size, scale, rotation...
So what you want is to extend Image.
The stage is not responsible for the drawing, it is just the "manager", which tells the Actors to update and draw themself. As much as i know it actually calls draw only for those Actors, which are inside the camera, as others are not visible and so they don't have to be drawn.

AS3 Stage3D: how to render all triangles with an overall alpha?

I am working on a 2D AS3 project, where the different layers are rendered via Stage3D, in a single drawTriangles() call, as a single mesh.
(if you are familiar with the BunnyMark GPUSprite mini render engine, that will give you an idea: http://www.bytearray.org/?p=4074)
What I would like is to draw one of these entire 'render layers', with an overall alpha transparency value, that would apply to ALL triangles drawn, adding to their own alpha values.
IE I am not looking to change the alpha by using textures with alpha transparency or via having to go through setting each triangle separately to have the same alpha: I want a master switch that would affect the alpha value of everything that is drawn? ( something computationally cheap)
Is this possible? Perhaps via a Shader, or a setProgramConstantsFromVector command?
Well you could render your layer to a texture, then you could put this texture on the stage with the alpha you want, this way your whole layer would have the same alpha!
You can do this in two ways, the first way is to render it to a texture, and display that texture with Stage3D and create a shader that adjusts the alpha.
The second way is rendering it to a bitmapData, and displaying it on the normal stage. I'll give an example for this way:
var bmd:BitmapData = new BitmapData(renderWidth, renderHeight, true, 0);
var bit:Bitmap = new Bitmap(bmd);
bit.alpha = 0.5;
addChild(bit);
//In your render loop at the beginning
context3D.renderToBitmapData(bmd);

AS3 Is it possible to duplicate a Shape object?

I'm trying to make a shape available for duplicating. Here's an explanation of what I've done, what I'm trying to do, and where I'm stuck:
Drew a shape manually in the Flash IDE (paintbrush).
Created a new movieclip containing the shape; exports as a class.
Instantiate the class (var mc:MovieClip = new shapeMovieClip()).
Add a reference to the shape in mc that I want (var myShape:Shape = mc.getChildAt(0) as Shape;
This works perfect and I now have my shape, but how can I duplicate it without instantiating the parent MovieClip class - is it possible?
I've tried creating a new shape and using the copyFrom() graphics method with no avail, I believe this method just copies draw calls when they're made on the referenced graphics and instead I just have a reference of a shape that's already been drawn.
Right now I'm extending the movieclip as a sprite instead, instantiating, pulling the shape from the parent and saving its reference, and then nulling the sprite. Does anyone know of a better, more lightweight, strategy for duplicating Shapes in this manner?
Basically depends on whether you need to scale your shapes. If you don't, and you can work it out with a fixed sized bitmap representation of the shape, then you will get much better performance drawing your shape to a BitmapData (it's called rasterisation) and instanciating Bitmap objects (as other commenters have pointed out). The code would go something like this:
var base:Sprite = new shapeMovieClip();
var bmd:BitmapData = new BitmapData(base.width, base.height, true, 0);
bmd.draw(base);
var clip1:Bitmap = new Bitmap(bmd);
var clip2:Bitmap = new Bitmap(bmd);
If you do need to scale the clips, you will get pixelation using bitmaps. When scaling down Bitmap.smoothing can help to some extent (also when rotating), but if you need to scale up, you will probably have to use some kind of mip-mapping. This is basically creating a few bitmaps of the shape at different scale levels, and then swap them depending on the current scale. Coding this has some complexity (using a helper parent to adjust the scale can help) but it will definitely perform better than using many shape symbols (with or without a sprite parent).
This is very old, but it still comes up high in Google, so I just wanted to share a true shape duplicating method:
var shapeonstage:Shape = shapeMadeInIDE;
var g:Vector.<IGraphicsData> = shapeonstage.graphics.readGraphicsData();
var shapecopy:Shape = new Shape();
shapecopy.graphics.drawGraphicsData(g)
And boom. It works. Had to share this because it would have helped me a looooong time ago and in so many ways.
UPDATE:
There is some clarification I'd like to add why you would want to use this method, for duplicating AND for storing references to Shapes that are within an swf.
If you target a Shape object on the stage or in a movie clip, the Flash Rendering engine does something strange. It will RECYCLE Shape objects to render new graphics thus making your Shape reference point to a COMPLETELY different rendering.
For example:
Create an fla with a movieclip.
Inside the movie clip make 10 frames.
On each frame, draw a different shape
In your code, get a reference to the shape (The Shape on Frame 1)
Draw and verify your shape (draw to a bitmap then put the bmp on stage)
Now let the flash engine play for 5 frames
Draw and verify your shape again
The second time you draw your shape without EVER reassigning your shape reference, will SOMETIMES yield a completely different shape.
Just know, this little quirk can leave you pulling your hair out if you don't know what you're looking for :)

Adding a object to a bitMapData

As of right now. I have 3 objects. One BitMap that acts as my canvas. And 2 bitmapDatas. One is my buffer and another is my tiles. I am creating a tiling effect for a game. I would like to take my tile:BitMapData, and turn it into a custom object. reason being is I want each tile to be interactive. So I can click on each one. Is it possible to turn my bitMapData that represents a tile, into a custom object that has properties and methods. Sort of like a movie clip. and draw it into my buffer ?? Could I create a new class that extends bitMapData ?? Or would I have to get rid of the buffer and draw the tile objects directly into the BitMap ??
In other words, what is the best way to put Sprite or a tile into a BitMapData object or even a Bitmap.
First of all, BitmapData and Bitmap are not interchangeable. They are two very different things. The BitmapData class contains bitmap pixel data, and allows you to manipulate that pixel data, e.g. draw to it, change the color of particular pixels, et c. There is no way of displaying a BitmapData directly, i.e. by adding it to the display list.
The Bitmap class, on the other hand, is a DisplayObject, like MovieClips and Sprites, which you can add to the display list. It's single purpose is to render a BitmapData in the display list. In fact, it is not even interactive, so you cannot detect clicks directly on a Bitmap instance, for example.
On to your question: If you have a bitmap data that contains a tile sprite, and you want to draw that tile in another bitmapdata, you can use the BitmapData.draw() method, or the BitmapData.copyPixels() method. The latter is one of the fastest methods you can use on any BitmapData, so I would highly recommend it.
Depending on your particular application, it might not be beneficial to draw everything in a bitmap at all. It sounds as if you want to be able to detect click events on all the tiles, which makes me think that you would probably benefit from having them be separate DisplayObjects, e.g. Sprites.
If you want to, you can create a Tile class that extends Sprite, and draws a BitmapData using a bitmap fill. That way, you can have any properties you want, and also detect mouse events on the tile instances.
package
{
/* ... imports ... */
public class Tile extends Sprite
{
private var _solid : Boolean;
public function Tile(bmp : BitmapData, solid : Boolean)
{
this.graphics.beginBitmapFill(bmp, null, false, true);
this.graphics.drawRect(0, 0, bmp.width, bmp.height);
_solid = solid;
}
/**
* Sample custom property. Could be used to define whether a tile
* is solid, e.g. the player cannot pass it.
*/
public function get isSolid() : Boolean
{
return _solid;
}
}
}
This class could simply be instantiated for every tile in your game, passing in the bitmap data that should be drawn in the tile. You could also listen for events on such a tile instance.
var tile : Tile;
tile = new Tile(myBitmapData, false);
tile.x = 200;
tile.y = 200;
tile.addEventListener(MouseEvent.CLICK, handleTileClick);
addChild(tile);
This way, you don't have to use the Bitmap class at all to render the tiles. They can be added directly to the display list.
I figure a better solution for when you want to select certain parts of the tile without effecting the position of the sprite itself
theMatrix.translate(30,0);
this.graphics.beginBitmapFill(tileImage,theMatrix);
//this.graphics.drawRect(0, 0,tWidth ,tHeight );
this.graphics.endFill();
Your right, leave drawRect at 0, 0. using Matrix.Translate, allows you to move the positioning of what part of the tile you want, without affecting the sprite position itself.