cocos2dx 3.10 图片五种适配方式及大屏解决法
2018-05-18 本文已影响0人
凉拌姨妈好吃
市面上有各种各样的手机,手机屏幕大小也各异,那么在开发过程中就不能只使用一套资源,需要根据不同的屏幕大小使用不同的资源。
我们前面有介绍过,当我们初始化glView是时候,我们有使用过一个函数来设计分辨率,传入的函数分别为:开发者自定义的宽长(称为设计尺寸),适配方式
glview->setDesignResolutionSize(designResolutionSize.width,
designResolutionSize.height,
ResolutionPolicy::EXACT_FIT);
适配方式在3.10里有五种方式:
EXACT_FIT,NO_BORDER ,SHOW_ALL,FIXED_HEIGHT,FIXED_WIDTH
我们根据源码来看看这几种方式是如何计算的,才能让图片资源适应屏幕
void GLView::updateDesignResolutionSize()
{
if (_screenSize.width > 0 && _screenSize.height > 0
&& _designResolutionSize.width > 0 && _designResolutionSize.height > 0)
{
_scaleX = (float)_screenSize.width / _designResolutionSize.width;
_scaleY = (float)_screenSize.height / _designResolutionSize.height;
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
_scaleX = _scaleY = MAX(_scaleX, _scaleY);
}
else if (_resolutionPolicy == ResolutionPolicy::SHOW_ALL)
{
_scaleX = _scaleY = MIN(_scaleX, _scaleY);
}
else if ( _resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
_scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
}
else if ( _resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
_scaleY = _scaleX;
_designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
}
// calculate the rect of viewport
float viewPortW = _designResolutionSize.width * _scaleX;
float viewPortH = _designResolutionSize.height * _scaleY;
_viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH);
// reset director's member variables to fit visible rect
auto director = Director::getInstance();
director->_winSizeInPoints = getDesignResolutionSize();
director->_isStatusLabelUpdated = true;
director->setGLDefaultValues();
}
}
这里定义了缩放因子,是屏幕尺寸与设计尺寸的比
_scaleX = (float)_screenSize.width / _designResolutionSize.width;
_scaleY = (float)_screenSize.height / _designResolutionSize.height;
- 无边界模式,为了使屏幕不存在黑边,当图片尺寸不够大,会将图片放大,那么一边补齐了黑边,另外一边可能就会露出屏幕外。所以在计算的时候,我们需要最大的缩放因子,如果缩放因子太小,那么就会有边界。
_scaleX = _scaleY = MAX(_scaleX, _scaleY);
NoBorder
- SHOW_ALL是按比例伸缩,全屏展示(大图铺满屏幕,小图留有黑边)。因为需要将图片全部展示,所以我们不能选择最大的缩放因子,最大的缩放因子会超出屏幕外,所以我们必须选择最小的缩放因子
_scaleX = _scaleY = MIN(_scaleX, _scaleY);
SHOW_ALL
- FIXED_HEIGHT 固定设计高度,但是会修改设计宽度,使设计宽度等于原宽度与高度缩放因子的比
_scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
- FIXED_WIDTH反之
viewport就是设备上可以来显示我们应用的那一块区域,其实也就是我们获得的frame大小。需要设置viewport画出的矩形大小,参数为矩形的起点位置(也就是左下角),长宽。
// calculate the rect of viewport
float viewPortW = _designResolutionSize.width * _scaleX;
float viewPortH = _designResolutionSize.height * _scaleY;
_viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH);
iphoneX的铁刘海遮挡组件的解决方法
我的思路:定高不定宽,底图做宽,手动处理横向左边的偏移