gpt4 book ai didi

android - 如何通过 JNI 将图像从 Java 传递到 Cocos2d-x?

转载 作者:搜寻专家 更新时间:2023-11-01 07:57:18 27 4
gpt4 key购买 nike

我需要通过 JNI 将图像数据(如 drawable)从 java 端传递到 cocos2d-x。我该如何实现? JNI函数的参数应该是什么,在cocos2d-x端如何转换?

最佳答案

  1. 为 JNI 创建一个 Java 接口(interface),例如:

    public static native void setBG(int[] raw, int width, int height);
  2. 在 C++ 代码中做:

    //Use static variable here for simplicity

    int *imagedata;
    int staticwidth;
    int staticheight;
    Texture2D *userBackgroundImage;



    void Java_com_my_company_JniHelper_setBG(JNIEnv* env, jobject thiz, jintArray raw, jint width, jint height)
    {
    jint *carr;
    carr = env->GetIntArrayElements(raw, 0);
    if(carr == NULL) {
    return; /* exception occurred */
    }
    ssize_t dataLen = (int)width * (int)height;
    int *data = new int[dataLen];
    for (long i = 0; i < dataLen; i++)
    {
    data[i] = carr[i];
    }
    imagedata = data;//Make a copy because it need to be done in GLThread
    staticwidth = (int)width;
    staticheight = (int)height;
    env->ReleaseIntArrayElements(raw, carr, 0);
    LOGD("set image: %d * %d", width, height);
    }

然后在 duration layer init 或其他 cocos2d-x 代码中调用以下方法:

    void createImage(const void *data, ssize_t dataLen, int width, int height)
{
Texture2D *image = new Texture2D();
if (!image->initWithData(data, dataLen, Texture2D::PixelFormat::BGRA8888, width, height, Size(width, height)))
{
delete image;
delete imagedata;
image = NULL;
imagedata = NULL;
userBackgroundImage = NULL;
return;
}
delete imagedata;
imagedata = NULL;
userBackgroundImage = image;
}

然后您可以使用 Texture2D 对象创建 Sprite 或做任何您想做的事情

  1. 要从 java 调用此代码:

    public static int[] BitmapToRaw(Bitmap bitmap) {
    Bitmap image = bitmap.copy(Bitmap.Config.ARGB_8888, false);
    int width = image.getWidth();
    int height = image.getHeight();
    int[] raw = new int[width * height];
    image.getPixels(raw, 0, width, 0, 0, width, height);
    return raw;
    }

    Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
    JniHelper.setBG(BitmapToRaw(image), image.getWidth(), image.getHeight());

关于android - 如何通过 JNI 将图像从 Java 传递到 Cocos2d-x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com