现在的位置: 首页 > 综合 > 正文

Cocos2d和UIKit的结合使用

2013年12月02日 ⁄ 综合 ⁄ 共 1389字 ⁄ 字号 评论关闭

额,题目写的有点大,其实这篇随笔只是想Mark下Cocos2d中对UIView的使用。

Cocos2d中想使用UIView等UIKit系的控件,最常用常见的方法,就是通过openGLView来做,虽然这个非常简单,还是简述下吧。

比如,现在我想在cocos2d中使用UIImageView这个控件,非常简单,直接上代码。

CGRect frame = [[[CCDirector sharedDirector] openGLView] frame];
_animateImageView = [[UIImageView alloc] initWithFrame:frame];
[[[CCDirector sharedDirector] openGLView] addSubview:_animateImageView];

不用了的时候。

[_animateImageView release];
[_animateImageView removeFromSuperview];

诺,这样呢,有一个问题,使用的UIImageView若不remove掉的话总是显示在最上面,再加个Sprite啥的也加不上去。恰好,这次需要的图比较大(320*480),还想借助UIImageView的动画功能,这下郁闷了。

怎么样才能即能让他顺利展示又能再上面添加Sprite或者CCMenu等呢。

 

OK, 直接给出解决方案吧。因为一旦采用openGLView addSubView的话肯定是不行的,那一个解决思路是在openGLView下插入一层View, 同时把openGLView设置成透明的,这样不就行了。

代码如下,首先要动的是AppDelegate,在openGLView下加入一层。

复制代码
//Set glView by wordsworth Mar.26    
[glView setMultipleTouchEnabled:YES];
glView.opaque = NO;
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);


//add a view by wordsworth Mar.26, in order to insert another view in MainBoardLayer
overView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
overView.opaque = NO;
overView.backgroundColor = [UIColor clearColor];
[overView addSubview:glView];

[window addSubview:overView];
复制代码

最后,把我们的ImageView尽情的写入openGLView下面吧,这样在上面加上各种各样的CCSprite、CCMenu等不用担心不显示啦。

AppDelegate * delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.overView insertSubview:_animateImageView belowSubview:[[CCDirector sharedDirector] openGLView]];

其他的UIKit控件也差不多可以按这个套路来了。

抱歉!评论已关闭.