最近有个需求需要从手机上获取相册图片,并且需要传回到Unity中,经过几天的开发终于完成,以下为开发的记录:
工具版本
- Unity5.6
安卓
Android Studio 3.0 Unity导出Gradle项目
使用gradle:2.3.3
compileSdkVersion 26
buildToolsVersion ‘26.0.2’
targetSdkVersion 26
IOS
Xcode 9.4
ios 9.0 +
安卓端
本来打算自己实现,后来发现发现网上的资料大多数都没能解决我的需求,于是转而使用了一个口碑很好的插件 PictureSelector
在build.gradle中增加以下代码来完成PictureSelector插件的导入:
`allprojects repositories { ...
jcenter() maven { url 'https://jitpack.io' } google() }}apply plugin: 'com.android.application'dependencies { ... compile 'com.github.LuckSiege.PictureSelector:picture_library:v2.2.3'}`
第一次见到了上面的增加插件的方式,简单暴力有效,虽然导入插件之后,发现无法编译通过,报以下的错误:
You need to use a Theme.Appcompat theme(or descendant) with this activity
(太长这里只写了有效部分)
根据报错提示
把 AndroidManifest.xml中android:theme改成如下即可,修改好的 AndroidManifest.xml文件要放到Plugins/Android文件夹下,不然每次导出gradle项目都会被覆盖。
android:theme="@style/Theme.AppCompat.Light.NoActionBar" tools:replace="android:theme">;
UnityPlayerActivity.java
`public void takeTexture() { PictureSelector.create(UnityPlayerActivity.this) .openGallery(PictureMimeType.ofImage()) .theme(com.luck.picture.lib.R.style.picture_default_style) .maxSelectNum(1) .imageSpanCount(4) .selectionMode(PictureConfig.SINGLE) .previewImage(true) .isCamera(false) .enableCrop(true) .compress(true) .withAspectRatio(1, 1) .freeStyleCropEnabled(false) .showCropFrame(true) .showCropGrid(true) .cropCompressQuality(90) .minimumCompressSize(10) .cropWH(128, 128) .rotateEnabled(true) .scaleEnabled(true) .isDragFrame(false) .selectionMedia(selectList) .forResult(PictureConfig.CHOOSE_REQUEST); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.i("Unity", "onActivityResult requestCode = " + requestCode + "resultCode = " + resultCode); if (resultCode == RESULT_OK) { switch (requestCode) { case PictureConfig.CHOOSE_REQUEST: selectList = PictureSelector.obtainMultipleResult(data); // 1.media.getPath(); 为原图path // 2.media.getCutPath();为裁剪后path,需判断media.isCut();是否为true // 3.media.getCompressPath();为压缩后path,需判断media.isCompressed();是否为true for (LocalMedia media : selectList) { if (media.isCompressed()) { if (media.isCut()) { String path = media.getCompressPath(); Log.i("Unity", " Cut 图片-----》 " + path); Bitmap bitmap = BitmapFactory.decodeFile(path); Log.d("Unity", "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight());
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); try { byte[] bytes = baos.toByteArray(); byte[] encode = Base64.encode(bytes, Base64.DEFAULT); String encodeString = new String(encode); UnityPlayer.UnitySendMessage("GameLogic", "OnTakeTexture", encodeString);
baos.flush(); baos.close(); } catch (IOException e) { UnityPlayer.UnitySendMessage("GameLogic", "OnTakeTexture", ""); e.printStackTrace(); } } } else { Log.i("Unity No", "图片-----》 " + media.getPath()); } } } } else { UnityPlayer.UnitySendMessage("GameLogic", "OnTakeTexture", ""); } }`
IOS端
这里参考了网上写法
sdk.h
@interface IOSSDK:UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>@end
sdk.mm
`@implementation IOSSDK-(void)openAlbum{ UIImagePickerController *picker = [[UIImagePickerController alloc]init]; picker.delegate = self; picker.allowsEditing = true; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:^{
}];}-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ UnitySendMessage("GameLogic", "OnTakeTexture", ""); [picker dismissViewControllerAnimated:YES completion:nil];}-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ UIImage *image = info[UIImagePickerControllerEditedImage]; UIImage *image2; UIGraphicsBeginImageContext(CGSizeMake(128, 128)); [image drawInRect:CGRectMake(0, 0, 128, 128)]; image2 = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
NSData *imgData; if (UIImagePNGRepresentation(image2) == nil) { imgData = UIImageJPEGRepresentation(image2, 1); }else{ imgData = UIImagePNGRepresentation(image2); } NSString *_encodeImageStr = [imgData base64EncodedStringWithOptions:0]; UnitySendMessage("GameLogic", "OnTakeTexture", _encodeImageStr.UTF8String); [picker dismissViewControllerAnimated:YES completion:nil];}extern "C" {
IOSSDK *iosSdk = nil; void InitSDK() { iosSdk = [[IOSSDK alloc] init]; }
void IOSTakeTexture(){ UIViewController *vc = UnityGetGLViewController(); [vc.view addSubview:iosSdk.view]; [iosSdk openAlbum];`
选择照片之后报错
errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 “query cancelled” UserInfo={NSLocalizedDescription=query cancelled}
经过网上查找发现以下解决方案
Product -> Scheme -> EditScheme -> Run(Debug)
如下图所示
OS_ACTIVITY_MODE disable
Unity端
PlatfromUti.cs
`#if UNITY_IOS[DllImport("__Internal")]public static extern void IOSTakeTexture();#endif
public static void CallAndorid(string funcName, params object[] args)
{
try
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic
///安卓或IOS获取相册插件public void TakeTexture(){#if UNITY_ANDROID PlatfromUti.CallAndorid("takeTexture");#elif UNITY_IOS PlatfromUti.IOSTakeTexture();#endif}/// <summary>/// 移动端获取图片回调/// </summary>/// <param name="encodeTexture">图片的base64字符串</param>void OnTakeTexture(string encodeTexture){ Texture2D texture = new Texture2D(128, 128); //移动端获取图片失败 if (string.Equals(encodeTexture, "")) { //获取图片失败或取消获取 } else { byte[] bytes = Convert.FromBase64String(encodeTexture); texture.LoadImage(bytes); texture.Apply(); //解析图片成功 }}
在需要的地方调用上面的TakeTexture方法,在OnTakeTexture中将收到移动端选择的图片的回调,然后使用C#将base64字符串转乘Unity中的Texture即可使用选择的图片。
欢迎扫码关注,获得精彩内容
各位客官,觉得有用,点个赞分享一下吧~
本文分享自微信公众号 - 游戏人的开发分享(No_2SeeYou)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。