您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Unity3D 的 iOS 外掛開發:打造原生相簿插件

編輯:iOS 開發綜合

Unity3D 是功能強大的跨平台遊戲引擎,但终究不可能把每個平台的每項能力都包裝成 API,尤其是一些比較新的系統功能。這時候就得自己撰寫原生插件來補齊。本文示範如何開發一個名為 GlobalBrowser 的 iOS 相簿插件:它會自動掃描 Documents 目錄,並用照片牆形式展示,展示部分 reuse 了 Objective-C 開源元件 MWPhotoBrowser。

準備工作

本文使用 Unity 5 與 Xcode 6.2。目前只有 Unity 4.6 與 Unity 5 支援 arm64,而且只有 Unity 5 允許在插件中使用子目錄。引入 Objective-C 程式碼的方式有三種:原始碼、靜態庫(.a)與 Framework(iOS 8 起),這次我們選擇最直覺的純原始碼方式。

一、撰寫原生程式碼

步驟 1:新建 iOS 專案 PhotoBrowser,在專案目錄下建立 Library 資料夾。

步驟 2:把 MWPhotoBrowser 及其相依的其他開源程式碼複製進 Library,並加入 Xcode 專案。

步驟 3:建立 GlobalBrowser 目錄,然後建立 DVIGlobalBrowser 類。為簡化起見,這裡只實作幾個類方法,並用一個靜態變量保存物件。

#import <Foundation/Foundation.h>

@interface DVIGlobalBrowser : NSObject
+ (void)show;
+ (void)dismiss;
@end

///////////// 實現代碼 /////////////

#import "DVIGlobalBrowser.h"
#import <UIKit/UIKit.h>
#import "MWPhotoBrowser.h"
#import "MWPhoto.h"

static DVIGlobalBrowser *sharedInstance = nil;

@interface DVIGlobalBrowser () <MWPhotoBrowserDelegate> {
    NSArray *_photosArray;
    NSString *_photoDir;
}
@property (nonatomic, strong) MWPhotoBrowser *photoBrowser;
@end

@implementation DVIGlobalBrowser

+ (void)initialize {
    sharedInstance = [[DVIGlobalBrowser alloc] init];
    sharedInstance.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:sharedInstance];
    sharedInstance.photoBrowser.displayActionButton = YES;
    sharedInstance.photoBrowser.displayNavArrows = YES;
    sharedInstance.photoBrowser.displaySelectionButtons = NO;
    sharedInstance.photoBrowser.alwaysShowControls = NO;
    sharedInstance.photoBrowser.zoomPhotosToFill = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    sharedInstance.photoBrowser.wantsFullScreenLayout = YES;
#endif
    sharedInstance.photoBrowser.enableGrid = YES;
    sharedInstance.photoBrowser.startOnGrid = YES;
    sharedInstance.photoBrowser.enableSwipeToDismiss = YES;
}

+ (void)show {
    [sharedInstance loadPhotos];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:sharedInstance.photoBrowser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    UIWindow *appWin = [UIApplication sharedApplication].keyWindow;
    [appWin.rootViewController presentViewController:nc animated:YES completion:nil];
    [sharedInstance.photoBrowser reloadData];
}

+ (void)dismiss {
    [sharedInstance.photoBrowser dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadPhotos {
    if (_photoDir == nil) {
        _photoDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    }
    NSArray *array = [[NSFileManager defaultManager] subpathsAtPath:_photoDir];
    _photosArray = array;
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photosArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    NSString *filename = _photosArray[index];
    NSString *path = [_photoDir stringByAppendingPathComponent:filename];
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:path]];
    return photo;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    NSString *filename = _photosArray[index];
    NSString *path = [_photoDir stringByAppendingPathComponent:filename];
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL fileURLWithPath:path]];
    return photo;
}

@end

步驟 4:Unity3D 那邊只認得 C/C++ 函式,因此還需要再包一層,用 extern C 把必要函式導出。

// .h 檔案中
extern C void showPhotoBrowser(void);

// .m 檔案中
void showPhotoBrowser(void) {
    [DVIGlobalBrowser show];
}

void dismissPhotoBrowser(void) {
    [DVIGlobalBrowser dismiss];
}

步驟 5:在獨立的 iOS 專案中先測試 DVIGlobalBrowser,確認原生層没问题再往 Unity 整合,能省下不少交叉除錯的時間。

二、撰寫 C# 介面

要在 Unity3D 中呼叫 Objective-C 程式碼,關鍵是寫好 C# 的 P/Invoke 宣告。在 GlobalBrowser 資料夾中建立 PhotoBrowser.cs。

public class PhotoBrowser
{
    // 引入 C 語言中的函式
    [DllImport("__Internal")]
    private static extern void showPhotoBrowser();

    // 暴露給 C# 的函式
    public static void showPhotoBrowserEx()
    {
        // 平台判斷,避免在編輯器或其他平台呼叫
        if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            showPhotoBrowser();
        }
    }
}

三、測試專案

在 Unity3D 的場景中加入按鈕。若沒用過截圖功能,要特別注意儲存路徑。

using UnityEngine;
using System.Collections;

public class MyFile : MonoBehaviour
{
    void OnGUI()
    {
        // 建立按鈕,用來顯示相簿
        if (GUI.Button(new Rect(100, 100, 100, 100), "Show"))
        {
            PhotoBrowser.showPhotoBrowserEx();
        }

        // 建立截圖按鈕
        if (GUI.Button(new Rect(100, 220, 100, 100), "Save"))
        {
            var savePath = Application.persistentDataPath + "/" + (Random.value * 100) + "image.png";
            print(savePath + " <---> Capture");
            // 截圖並存檔到 Documents 目錄
            Application.CaptureScreenshot((Random.value * 100) + "image.png");
        }
    }
}

整條鏈路可以概括為:Unity C# → extern C 橋接函式 → Objective-C 類 → 系統 API。只要守住這層分邊界,後續要替換照片瀏覽器或加上相簿寫回功能,都只需動原生那一側。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved