首页 > 代码库 > Cocos2d-x_3.2 Demo学习之VisibleRect类

Cocos2d-x_3.2 Demo学习之VisibleRect类

这个类主要提供屏幕各个特殊位置的坐标。附上头文件代码:

 1 class VisibleRect 2 { 3 public: 4     static cocos2d::Rect getVisibleRect();// 获取屏幕矩形 5  6     static cocos2d::Vec2 left();        // 左中, 7     static cocos2d::Vec2 right();        // 右中 8     static cocos2d::Vec2 top();        // 顶中 9     static cocos2d::Vec2 bottom();    // 底中10     static cocos2d::Vec2 center();        // 中心11     static cocos2d::Vec2 leftTop();    // 左顶12     static cocos2d::Vec2 rightTop();    // 右顶13     static cocos2d::Vec2 leftBottom();    // 左底14     static cocos2d::Vec2 rightBottom();    // 右底15 private:16     static void lazyInit();// 获取屏幕矩形17     static cocos2d::Rect s_visibleRect;// 用于保存屏幕矩形18 };

上面都是获得矩形特殊位置的函数,大概位置,请看如下图:

Rect(x,y,width,height)是以屏幕左上角为(0,0)基准,width是宽度,height是高度。在Cocos2d-x里可以分步表示成如下:

Vec2 origin;// 左上角坐标(x,y)
Size size;// 尺寸(width,height)

其实这个就是Rect类里的表示x,y,width,height的成员变量。

接下来我们来看VisibleRect.cpp文件,代码附上:

 1 void VisibleRect::lazyInit() 2 { 3     s_visibleRect = Director::getInstance()->getOpenGLView()->getVisibleRect(); 4 } 5  6 Rect VisibleRect::getVisibleRect() 7 { 8     lazyInit(); 9     return s_visibleRect;10 }11 // (0,width/2)12 Vec2 VisibleRect::left()13 {14     lazyInit();15     return Vec2(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height/2);16 }17 // (width,height/2)18 Vec2 VisibleRect::right()19 {20     lazyInit();21     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height/2);22 }23 // (width/2,height)24 Vec2 VisibleRect::top()25 {26     lazyInit();27     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height);28 }29 // (width/2,0)30 Vec2 VisibleRect::bottom()31 {32     lazyInit();33     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y);34 }35 // (width/2,height/2)36 Vec2 VisibleRect::center()37 {38     lazyInit();39     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height/2);40 }41 // (0,height)42 Vec2 VisibleRect::leftTop()43 {44     lazyInit();45     return Vec2(s_visibleRect.origin.x, s_visibleRect.origin.y+s_visibleRect.size.height);46 }47 // (width,height)48 Vec2 VisibleRect::rightTop()49 {50     lazyInit();51     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y+s_visibleRect.size.height);52 }53 // (0,0)54 Vec2 VisibleRect::leftBottom()55 {56     lazyInit();57     return s_visibleRect.origin;58 }59 // (width,0)60 Vec2 VisibleRect::rightBottom()61 {62     lazyInit();63     return Vec2(s_visibleRect.origin.x+s_visibleRect.size.width, s_visibleRect.origin.y);64 }

这个类实现比较简单,就是获取特殊位置的坐标。

Cocos2d-x_3.2 Demo学习之VisibleRect类