簡體   English   中英

在Unity Android插件中訪問和使用圖像

[英]Accessing and using an image in an Unity Android Plugin

是的...我以前從未用C#或Java編寫任何東西,所以我在這方面可能完全錯了,很可能是一個簡單的答案,但是這里...

我有一個非常簡單的Unity應用,可以簡單地觸發一個android插件。 插件需要接受文本字符串和圖片,然后才能進行共享。

C#

using UnityEngine;
using System.Collections;
public class RunStuff : MonoBehaviour {
    AndroidJavaClass androidClass;
    AndroidJavaObject androidActivity;

    void Start () {
        Debug.Log ("----- UNTIY SCRIPT INIT ----- ");

        var pathToImage = Application.streamingAssetsPath + "/meagain.jpg";
        Debug.Log (pathToImage);

        AndroidJNI.AttachCurrentThread ();
        androidClass = new AndroidJavaClass("com.something.something.Plugin");
        androidActivity = androidClass.GetStatic<AndroidJavaObject>("mContext");
        androidActivity.Call("Plugin", pathToImage , "SOME TEST STRING");

        Debug.Log ("----- UNTIY SCRIPT END ----- ");
    }
}

Java的

package com.something.something;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.unity3d.player.UnityPlayerActivity;

public class Plugin extends UnityPlayerActivity {
    public static Context mContext;
    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        mContext = this;
    }

    public void Plugin(String imagePath, String message) {
        Log.d("TAG", imagePath);
        Log.d("TAG", message);

        // HERE I NEED TO BE ABLE TO USE THE IMAGE
    }
}

所有這些都可以正常工作,因為在Java類中我收到了imagePath和消息。但是,我根本無法從imagepath中獲取圖像。

該圖像在Unity項目中的StreamingAssets / meagain.jpg下。 如果我提取生成的apk,則可以看到該文件,但是所有嘗試都失敗了!

任何人有任何想法嗎?!

    Texture2D myTex;
string url = "file://"+Application.streamingAssetsPath + "/" + textureName;    
WWW www = new WWW(url );
    myTex = www.texture;

我知道如何從streamignAssets加載東西的唯一方法。

在Android Java中,您將使用類似

 InputStream in = mContext.getAssets().open("meagain.jpg");

或者可能

 InputStream in = Plugin.class.getClassLoader().getResourceAsStream("meagain.jpg");

沒有經過測試,但是值得一試!

還做了一些研究:

/* from your subroutine */
Bitmap newBitmap = getBitmapFromAsset(mContext, imagePath);

/* new function to get Bitmap From Asset */
public static Bitmap getBitmapFromAsset(Context context, String imagePath) {
  AssetManager assetManager = context.getAssets();

  InputStream istr;
  Bitmap bitmap = null;
  try {
    istr = assetManager.open(imagePath);
    bitmap = BitmapFactory.decodeStream(istr);
  } catch (IOException e) {
    // handle exception
  }

  return bitmap;
}

同樣不要忘記Bitmap,AssetManager,InputStream,BitmapFactory和IOException的導入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM