Saturday, February 28, 2009

2. Draw a red block in c++


#define LOG_NDEBUG 0
#define LOG_TAG "NativeUITest"
#include <utils/Log.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>

#include <utils/IPCThreadState.h>
#include <utils/ProcessState.h>
#include <ui/SurfaceComposerClient.h>
#include <ui/Surface.h>
#include <ui/ISurfaceComposer.h>
#include "SkCanvas.h"
#include "SkDevice.h"

using namespace android;

static inline SkBitmap::Config convertPixelFormat(PixelFormat format)
{
/* note: if PIXEL_FORMAT_XRGB_8888 means that all alpha bytes are 0xFF,
then we can map to SkBitmap::kARGB_8888_Config, and optionally call
bitmap.setIsOpaque(true) on the resulting SkBitmap (as an accelerator)
*/
switch (format) {
case PIXEL_FORMAT_RGBA_8888: return SkBitmap::kARGB_8888_Config;
case PIXEL_FORMAT_RGBA_4444: return SkBitmap::kARGB_4444_Config;
case PIXEL_FORMAT_RGB_565: return SkBitmap::kRGB_565_Config;
case PIXEL_FORMAT_A_8: return SkBitmap::kA8_Config;
default: return SkBitmap::kNo_Config;
}
}

int main(int argc, char** argv)
{
sp<ProcessState> proc = ProcessState::self();
proc->startThreadPool();
int pid = getpid();
int nState = 0;
sp<SurfaceComposerClient> client = new SurfaceComposerClient;
sp<Surface> surface(client->createSurface(pid, 0, 176, 144, PIXEL_FORMAT_OPAQUE, ISurfaceComposer::eFXSurfaceNormal));

//set surface layer to INT_MAX
client->openTransaction();
//nState = surface->setSize(176, 144);
nState = surface->setPosition(100, 200);
nState = surface->setLayer(INT_MAX);
nState = surface->show();
client->closeTransaction();

//Start painting...
client->openTransaction();
Rect rect(0,0,176,144);
Region dirtyRegion(rect);
Surface::SurfaceInfo info;
status_t err = surface->lock(&info, &dirtyRegion);
if(err < 0)
{
client->closeTransaction();
IPCThreadState::self()->stopProcess();
return -1;
}
SkCanvas myCanvas;
SkCanvas* canvas = &myCanvas;
SkBitmap bitmap;
bitmap.setConfig(convertPixelFormat(info.format), info.w, info.h, info.bpr);
bitmap.setPixels(info.bits);
canvas->setBitmapDevice(bitmap);
canvas->clipRegion(dirtyRegion.toSkRegion());
int saveCount = canvas->save();
//paint hole
//canvas->drawColor(0, SkPorterDuff::kClear_Mode);
//paint a red block
canvas->drawARGB(255, 255, 0, 0);
canvas->restoreToCount(saveCount);
canvas->setBitmapDevice(SkBitmap());
nState = surface->unlockAndPost();
LOGI("surface->unlockAndPost, %d", nState);
client->closeTransaction();

sleep(10);
IPCThreadState::self()->stopProcess();
LOGI("quiting...");
return 0;
}

No comments:

Post a Comment