SurfaceTest.cpp
#include <cutils/memory.h>
#include <utils/Log.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <android/native_window.h>
using namespace android;
int main(int argc, char** argv)
{
// 设置线程池
sp<ProcessState> proc(ProcessState::self());
ProcessState::self()->startThreadPool();
// 创建与Surfaceflinger通信的客户端
sp<SurfaceComposerClient> client = new SurfaceComposerClient();
// 创建SurfaceControl并设置名称“resize”、宽高、像素格式,红色分量使用 5 位,绿色分量使用 6 位,蓝色分量使用 5 位。
sp<SurfaceControl> surfaceControl = client->createSurface(String8("resize"),
160, 240, PIXEL_FORMAT_RGB_565, 0);
//通过SurfaceControl获取一个Surface
sp<Surface> surface = surfaceControl->getSurface();
SurfaceComposerClient::Transaction t;
//设置Layer层级,数值越大层级越高
t.setLayer(surfaceControl, 100000)
.apply();
//SurfaceComposerClient::openGlobalTransaction();
//surfaceControl->setLayer(100000);
//SurfaceComposerClient::closeGlobalTransaction();
ANativeWindow_Buffer outBuffer;
//从BufferQueue中获取获取一个Buffer
surface->lock(&outBuffer, NULL);
//计算每个像素点的字节大小
ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
//
android_memset16((uint16_t*)outBuffer.bits, 0xF800, bpr*outBuffer.height);
//提交填充后的buffer
surface->unlockAndPost();
sleep(3);
surface->lock(&outBuffer, NULL);
android_memset16((uint16_t*)outBuffer.bits, 0x07E0, bpr*outBuffer.height);
surface->unlockAndPost();
sleep(3);
surface->lock(&outBuffer, NULL);
android_memset16((uint16_t*)outBuffer.bits, 0x001F, bpr*outBuffer.height);
surface->unlockAndPost();
sleep(3);
for (int i = 0; i < 100; i++) {
surface->lock(&outBuffer, NULL);
printf("%03d buff addr = 0x%x\n", i, (unsigned int)outBuffer.bits);
surface->unlockAndPost();
}
IPCThreadState::self()->joinThreadPool();
return 0;
}
Android.mk
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
SurfaceTest.cpp
LOCAL_SHARED_LIBRARIES := \
libcutils \
libutils \
libui \
libgui \
libbinder
LOCAL_MODULE:= SurfaceTest
LOCAL_MODULE_TAGS := tests
include $(BUILD_EXECUTABLE)
运行此程序,将在屏幕上的一块区域显示红绿蓝三颜色。亲测可用,程序很简单,但背后的显示系统框架却比较复杂。