Cocos2dx

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
_scaleX = _scaleY = MIN(_scaleX, _scaleY);
SHOW_ALL
 _scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX);

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的铁刘海遮挡组件的解决方法

我的思路:定高不定宽,底图做宽,手动处理横向左边的偏移

上一篇 下一篇

猜你喜欢

热点阅读