cocos2d-x调用ios的摄像头


最近在实现用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中很多类都不是非常理解,还需要多学习啊,以此励志,哈哈。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值