I've made a little class that might be useful to someone else. And maybe someone has can suggest some improvements? Perhaps I have missed something that is already included?
It is a sprite map, to put graphics for more than one sprite in one image. It is useful for animation for instance. The source is a complete runnable example.
main.cpp:
#include "MAHeaders.h"
#include "ma.h"
#include <MAUtil/Moblet.h>
#include <MAUI/Screen.h>
#include <MAUI/Widget.h>
using namespace MAUtil;
using namespace MAUI;
class SpriteMap
{
public:
SpriteMap(MAHandle image, int columns, int rows=1) :
image(image)
{
MAExtent e = maGetImageSize(image);
width = EXTENT_X(e) / columns;
height = EXTENT_Y(e) / rows;
srcRect.width = width;
srcRect.height = height;
}
void drawSprite(int x, int y, int column, int row=0, int transform=TRANS_NONE) {
srcRect.left = column * width;
srcRect.top = row * height;
dstPoint.x = x - (width >> 1);
dstPoint.y = y - (height >> 1);
maDrawImageRegion(image, &srcRect, &dstPoint, transform);
}
private:
MAHandle image;
int width;
int height;
MARect srcRect;
MAPoint2d dstPoint;
};
class MyWidget : public Widget, public TimerListener {
public:
MyWidget(int x, int y, int width, int height, Widget* parent) :
Widget(x, y, width, height, parent),
//backColor(
, why not?
spriteMap(STAR_SMAP, 8, 2),
startMs(maGetMilliSecondCount())
{
this->setBackgroundColor(0x000000);
//this->backColor = 0x000000; //This works
}
void drawWidget()
{
spriteMap.drawSprite(100, 100, (time>>6) & 7, 0);
spriteMap.drawSprite(100, 100, (-time>>7) & 7, 1);
}
void start()
{
MAUtil::Environment::getEnvironment().addTimer(this, 20, -1); // 50Hz, forever
}
void tick(int dt)
{
time += dt;
}
void runTimerEvent() {
int now = maGetMilliSecondCount();
int dt = now - startMs;
startMs = now;
tick(dt);
requestRepaint();
}
private:
SpriteMap spriteMap;
int startMs;
int time;
};
class MyScreen : public Screen {
public:
MyScreen() :
myWidget(0, 0, 0, 0, NULL)
{
myWidget.start();
setMain(&myWidget);
}
~MyScreen() {
}
private:
MyWidget myWidget;
};
class MAUIMoblet : public Moblet {
public:
MAUIMoblet():
screen()
{
screen.show();
}
void keyPressEvent(int keyCode) {
// todo: handle key presses
}
void keyReleaseEvent(int keyCode) {
// todo: handle key releases
}
~MAUIMoblet() {
}
private:
MyScreen screen;
};
extern "C" int MAMain() {
Moblet::run(new MAUIMoblet());
return 0;
};
gfx.lst:
.res STAR_SMAP .image "smap.png"
I just noticed that the image is not very explaining, since it is a white image with different alphas. You'll have to look at it with a different background colour somehow.
