Android代码:
public class MainActivity extends UnityPlayerActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PHOTO_REQUEST_CODE = 1;
private static final boolean DEBUG = false;
private String gameobjectName = "Main Camera";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void OpenGallery()
{
Intent intent = new Intent(Intent.ACTION_PICK,null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent, PHOTO_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(PHOTO_REQUEST_CODE == requestCode){
Uri uri = data.getData();
String imagePath = getImagePath(uri);
if(DEBUG){
Log.d(TAG, imagePath);
}
UnityPlayer.UnitySendMessage(gameobjectName, "GetImagePath", imagePath);
}
}
//获取到图片的地址
private String getImagePath(Uri uri)
{
if(null == uri) return null;
String path = null;
final String scheme = uri.getScheme();
if (null == scheme) {
path = uri.getPath();
} else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
path = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, proj, null, null,
null);
int nPhotoColumn = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (null != cursor) {
cursor.moveToFirst();
path = cursor.getString(nPhotoColumn);
}
cursor.close();
}
return path;
}
}
AndroidManifest.xml中添加权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Unity代码:
public class PhotoTest : MonoBehaviour {
public Button mOpenPhoto;
public Image mImage;
public Text mLog;
private void Start()
{
mOpenPhoto.onClick.AddListener(OpenPhoto);
}
//接通Android
private void OpenPhoto()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("OpenGallery");
}
//获取到图片的地址
public void GetImagePath(string imagePath)
{
if (imagePath == null)
return;
mLog.text = imagePath;
StartCoroutine("LoadImage",imagePath);
}
//加载纹理
private IEnumerator LoadImage(string imagePath)
{
WWW www = new WWW ("file://"+imagePath);
mLog.text = mLog.text + "\n www开始加载";
yield return www;
mLog.text = mLog.text + "\n www加载完成";
if (www.error == null)
StartCoroutine ("UpdataImage", www.texture);
else
mLog.text = mLog.text + "\n"+www.error;
}
//纹理转化为精灵
private IEnumerator UpdataImage(Texture2D texture)
{
mLog.text = mLog.text + "\n 开始转化为精灵";
Sprite sprite = Sprite.Create(texture, new Rect(0,0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
mImage.sprite = sprite;
mLog.text = mLog.text + "\n 转换结束";
yield return new WaitForSeconds(0.01f);
Resources.UnloadUnusedAssets();
}
}