前回はAndroid NDKに含まれるネイティブ描画のサンプルプロジェクト「bitmap-plasma」を見た。今回はそのプロジェクトを参考にネイティブ描画処理部分のみを抜き出した雛形プロジェクトを作る。
EasyProjectGenerator for Android Ver 1.00を利用してAndroid NDKプロジェクトを生成してEclipseに取り込む。

package com.Test107; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.view.View; import android.graphics.Bitmap; import android.graphics.Canvas; public class Test107Act extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new NativeView(this)); } static { System.loadLibrary("Test107jni"); } } class NativeView extends View { private Bitmap mBitmap; private static native void RenderBitmap(Bitmap bitmap); public NativeView(Context context) { super(context); final int W = 200; final int H = 200; mBitmap = Bitmap.createBitmap(W, H, Bitmap.Config.RGB_565); } @Override protected void onDraw(Canvas canvas) { RenderBitmap(mBitmap); canvas.drawBitmap(mBitmap, 0, 0, null); } }

#include <jni.h> #include <android/bitmap.h> /* this function is from Android NDK bitmap-plasma */ static uint16_t make565(int red, int green, int blue) { return (uint16_t)( ((red << 8) & 0xf800) | ((green << 2) & 0x03e0) | ((blue >> 3) & 0x001f) ); } static void DrawBitmap(AndroidBitmapInfo* pBitmapInfo, void* pPixels) { int yy; for(yy = 0; yy < pBitmapInfo->height; yy++) { int xx; uint16_t* pLine = (uint16_t*)pPixels; for(xx = 0; xx < pBitmapInfo->width; xx++) { pLine[xx] = make565(xx % 256,yy % 256,0); } // go to next line pPixels = (char*)pPixels + pBitmapInfo->stride; } } JNIEXPORT void JNICALL Java_com_Test107_NativeView_RenderBitmap(JNIEnv * env, jobject obj, jobject bitmap) { AndroidBitmapInfo info; void* pixels; int ret; if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) return; if (info.format != ANDROID_BITMAP_FORMAT_RGB_565) return; if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) return; DrawBitmap(&info,pixels); AndroidBitmap_unlockPixels(env, bitmap); }

LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := Test107jni LOCAL_SRC_FILES := Test107jni.c LOCAL_LDLIBS := -lm -llog -ljnigraphics include $(BUILD_SHARED_LIBRARY)
ソースコードの編集が終わったらファイルを保存してndk-buildによりビルドする。
そしてAndroidエミュレーターで実行するとネイティブの描画処理によるグラデーションが表示された。
※実際にはネイティブ側ではビットマップ処理のみ。描画はjava側で行っています、、、
プロジェクトファイルをダウンロード