您的位置:首页 > 移动开发 > Unity3D

只将unity的UI控件添加到iOS视图层,不显示unity的原生背景(二)

2017-04-18 14:27 656 查看
刚面试完,信心备受打击,项目经验不够就是容易受歧视。

继续更新吧。。。把自己这几个月学的分享一下

上一篇博客实现了将unity的相机背景改为透明的,能够显示出iOS的视图。

但是这时候,我们只能操作显示出来的iOS视图,不能点击unity的控件,那我们怎么才能实现点击呢?

在unityView.mm中,我们添加代码

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
//判断一下渲染API是否为metal,OpenGLES暂未实现
if(UnitySelectedRenderingAPI() == apiMetal)
{
// 获取渲染surface
UnityDisplaySurfaceMTL* surf = (UnityDisplaySurfaceMTL*)GetMainDisplaySurface();
// 渲染surface尺寸
CGSize s = ((CAMetalLayer*)self.layer).drawableSize;
// 得到点击坐标
CGPoint p = [self convertPoint:point toView:self];

// 坐标转换
CGFloat bw = self.bounds.size.width;
CGFloat bh = self.bounds.size.height;
CGFloat box = self.bounds.origin.x;
CGFloat boy = self.bounds.origin.y;
CGFloat x = (p.x - box)/bw * s.width;
CGFloat y = (p.y - boy)/bh * s.height;

// 得到上一次渲染的Texture
MTLTextureRef lastTex = surf->lastSystemColorRB;
// 获取Texture中此坐标的颜色值
MTLRegion region = MTLRegionMake2D(x, y, 1, 1);
Byte byteBuff[4];
[lastTex getBytes:byteBuff bytesPerRow:_surfaceSize.width*4 fromRegion:region mipmapLevel:0];
// 判断Alpha值
int a = byteBuff[3];
if(a > 0 )
{
return YES;
}
else
{
return NO;
}
}
return YES;
}


Classes/Unity/UnityRendering.h中的UnityDisplaySurfaceMTL结构声明中,添加

OBJC_OBJECT_PTR MTLTextureRef lastSystemColorRB,用来保存上一帧渲染Texture。

// Metal display surface

START_STRUCT(UnityDisplaySurfaceMTL, UnityDisplaySurfaceBase)

    OBJC_OBJECT_PTR CAMetalLayer* layer;

    OBJC_OBJECT_PTR MTLDeviceRef device;

    OBJC_OBJECT_PTR MTLCommandQueueRef commandQueue;

    OBJC_OBJECT_PTR CAMetalDrawableRef drawable;

    OBJC_OBJECT_PTR MTLTextureRef systemColorRB;

    OBJC_OBJECT_PTR MTLTextureRef targetColorRT;

    OBJC_OBJECT_PTR MTLTextureRef targetAAColorRT;

    OBJC_OBJECT_PTR MTLTextureRef depthRB;

    OBJC_OBJECT_PTR MTLTextureRef stencilRB;

    unsigned colorFormat; // [MTLPixelFormat]

    unsigned depthFormat; // [MTLPixelFormat]

    // add here

    OBJC_OBJECT_PTR MTLTextureRef lastSystemColorRB;

END_STRUCT(UnityDisplaySurfaceMTL)

在每次渲染前保存lastSystemColorRB。修改Classes/Unity/MetalHelper.mm的StartFrameRenderingMTL函数

在 surface->systemColorRB = [surface->drawable texture] 后面添加

surface->lastSystemColorRB = surface->systemColorRB。

这样就可以实现,既能点击unity的控件,又能点击iOS的视图了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: