cocos2d-x呼叫ios的攝像頭
阿新 • • 發佈:2019-02-06
最近在實現用cocos2d-x實現拍照的功能,在網上找了很多關於object-c和c++混編的資料,也找到如何呼叫攝像頭的方法,但是總是不能實現,於是糾結一天也沒有結果,今天找到了一篇cocos2d-x呼叫game center,覺得都是ios api,應該能找到靈感,於是按照這個思路去做,果然是實現了。先附上程式碼,其中還有很多不明白的地方。
首先mo建了兩個類,一個是c++的,一個是object-c的
Object-C我們需要建一個UIViewController類,因為我們要在裡面呼叫<UIImagePickerControllerDelegate,UINavigationControllerDelegate>這兩個委託
takePhoto.h
#import <UIKit/UIKit.h> @interface takePhoto : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate> -(void)snapImage:(id)sender; -(NSString *)findUniqueSavePath; -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; @end
takePhoto.m
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UIWindow * window = [[UIApplication sharedApplication]keyWindow]; [window addSubview:self.view]; UIButton * take = [UIButton buttonWithType:UIButtonTypeCustom]; [take setBackgroundColor:[UIColor whiteColor]]; [take addTarget:self action:@selector(snapImage:) forControlEvents:UIControlEventTouchUpInside]; [take setFrame:CGRectMake(20, 20, 50, 50)]; [self.view addSubview:take]; NSLog(@"I‘m here"); } -(void)snapImage:(id)sender{ UIImagePickerController * ipc = [[UIImagePickerController alloc]init]; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; ipc.delegate = self; ipc.wantsFullScreenLayout=YES; ipc.allowsImageEditing=NO; [self presentModalViewController:ipc animated:YES]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; [self dismissModalViewControllerAnimated:YES]; [picker release]; UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//儲存到預設相簿 }
cocos2d-x部分程式碼:
scene_photo.h
#ifndef __Test__scene_photo__
#define __Test__scene_photo__
#include "cocos2d.h"
using namespace cocos2d;
class scene_photo:public CCLayer{
public:
static CCScene * scene();
scene_photo();
};
#endif /* defined(__Test__scene_photo__) */
scene_photo.mm#include "scene_photo.h"
#include "takePhoto.h"
using namespace cocos2d;
CCScene * scene_photo::scene()
{
CCScene * scene = CCScene::node();
CCLayer * layer = new scene_photo;
scene->addChild(layer);
layer->release();
return scene;
}
scene_photo::scene_photo()
{
takePhoto * photo = [[takePhoto alloc]init];
[photo viewDidLoad];//要手動新增,否則無法顯示按鈕
}
這一步是需要將.cpp檔案改成.mm這樣才能呼叫object-c檔案 我是在HelloWorldScene.cpp裡新增一個menuItem,來跳轉到scene_photo場景中的,這裡就省略了。 這裡還有很重要的一步,就是將AppDelegat.cpp檔名改成AppDelegate.mm檔案,否則xcode會報錯。 作為初學者,對於ios中很多類都不是非常理解,還需要多學習啊,以此勵志,哈哈。