Android NDK 调用Skia进行底层绘图

Skia是Android的底层的图形库,最近看了一下参考了了网上的例子最初是这样做的就是从上层直接传一个Canvas再在底层获取它

运行的时候老是不成功,不过可以画图形,比如线、矩形等,最后在网上查了一下,大致是源代码版本和库不同导致的最后实在没法了,我就直接传一个Bitmap对象,再在底层

将文字和图形写在上面,这样就可以了

下面是底层代码:

#include "SkRect.h"
#include "SkImageEncoder.h"
static JNIEnv *env=NULL;
static int nMethods=1;
const char* classname="mytest/com/sam/NativeMethods";
extern "C"
{
	void jni_renderhello(JNIEnv *env,jobject ob,jobject bitmap);
};
static JNINativeMethod gMethods[] = {
	{
		"test","(Landroid/graphics/Bitmap;)V",(void *)jni_renderhello
	},
};
void jni_renderhello(JNIEnv * env, jobject  obj, jobject bitmap)  
{  
	AndroidBitmapInfo  info;  
	int*              pixels;  
	int ret;  
	ret = AndroidBitmap_getInfo(env, bitmap, &info);  
	ret = AndroidBitmap_lockPixels(env, bitmap, (void**)&pixels);  
	int width=(int)info.width;  
	int height=(int)info.height;  
	SkBitmap bmp = SkBitmap();  
	bmp.setConfig(SkBitmap::kARGB_8888_Config,width,height,0);  
	bmp.setPixels((void*)pixels);  
	SkCanvas backgroud(bmp);  
	SkPaint paint;
	paint.setColor(SK_ColorGRAY);
	SkRect rect;
	rect.set(0,0,width,height);
	backgroud.drawRect(rect,paint);
	paint.setColor(SK_ColorGREEN);
	const char *str="Hello Skia";
	paint.setTextSize(30);
	backgroud.drawText(str,strlen(str), 0, 100 , paint);
}
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
	jint result=-1;
	jclass clz=NULL;
	if(vm->GetEnv((void**)&env,JNI_VERSION_1_4)!=JNI_OK)
		return -1;
	clz=env->FindClass(classname);
	if(env->RegisterNatives(clz,gMethods,nMethods)<0)
		return -1;
	return JNI_VERSION_1_4;
}


这是java的调用

public class MyTestActivity extends Activity {
    /** Called when the activity is first created. */
	MyView view;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view=new MyView(this);
        setContentView(view);
    }
}
class MyView extends View
{
	public MyView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		NativeMethods method=new NativeMethods();
		Bitmap bm=Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(), Config.ARGB_8888);
		final Paint paint = new Paint();
		method.test(bm);
		canvas.drawBitmap(bm, 0, 0, paint);
	}
	
}
class NativeMethods
{
	public native void test(Bitmap canvas);
	static
	{
		System.loadLibrary("Skiademo");
	}
}



你可能感兴趣的:(Android)