您的位置:首页 > 编程语言 > C语言/C++

工作中重新封装编写的一系列工具函数(c/c++)

2016-05-26 16:36 489 查看
//

// JGUtil.cpp

//

#include "JGUtil.h"

#include "cocos2d.h"

#include "ui/CocosGUI.h"

USING_NS_CC;

//把targetNode添加到curNode里
void
JGUtil::replaceNodeParent(Node* curNode,
Node* targetNode)
{

//记录坐标

Vec2 pos = targetNode->getPosition();

Vec2 anchor = targetNode->getAnchorPoint();

int zOrder = targetNode->getLocalZOrder();

Node* parent = targetNode->getParent();

//这个一定要,不然出现各种奇爬问题

Size itemSize = targetNode->getContentSize();
targetNode->setPosition(Vec2(itemSize.width*anchor.x,itemSize.height*anchor.y));
targetNode->retain();
targetNode->removeFromParent();

//把ui加入到当前
curNode->addChild(targetNode);
curNode->setContentSize(itemSize);
targetNode->release();

//设置当前坐标
curNode->setPosition(pos);
curNode->setAnchorPoint(anchor);
curNode->setLocalZOrder(zOrder);

if(parent != nullptr)
parent->addChild(curNode);
}

void
JGUtil::setAllCascadeOpacityEnabled(cocos2d::Node *node)
{

node->setCascadeOpacityEnabled(true);

if(node->getChildrenCount()>0)
{

for(int i =
0 ; i< node->getChildren().size(); i++)
{

Node* child = node->getChildren().at(i);

setAllCascadeOpacityEnabled(child);
}
}
}

std::vector<std::string>
JGUtil::split(std::string str,std::string pattern) {

std::string::size_type pos;

std::vector<std::string> result;
result.clear();
str += pattern;//扩展字符串以方便操作

size_t size = str.size();

for(int i =
0; i< size; i++)
{
pos = str.find(pattern,i);

if(pos < size)
{

std::string s = str.substr(i,pos - i);
result.push_back(s);
i = (int)(pos + pattern.size()) -
1;
}
}

return result;
}

void
JGUtil::copyData(const
char* pFileName) {

if (isFileExist(pFileName)) {

return;
}

std::string strPath =
FileUtils::getInstance()->fullPathForFilename(pFileName);

log("strPath = %s",strPath.c_str());

ssize_t len = 0;

unsigned
char *data = NULL;
data =
FileUtils::getInstance()->getFileData(strPath.c_str(),
"r",&len);

log("len = %d",(int)len);

std::string destPath =
FileUtils::getInstance()->getWritablePath();
destPath += pFileName;

FILE *fp = fopen(destPath.c_str(),
"w+");

fwrite(data, sizeof(char), len, fp);

fclose(fp);

delete[] data;
data =
NULL;
}

bool
JGUtil::isFileExist(const
char* pFileName) {

if (!pFileName)

return
false;

std::string filePath =
FileUtils::getInstance()->getWritablePath();
filePath += pFileName;

FILE *fp = fopen(filePath.c_str(),
"r");

if (fp) {

fclose(fp);

return true;
}

return
false;
}

void
JGUtil::saveToFile(const
std::string &str,
const std::string filename)
{

std::string filePath =
FileUtils::getInstance()->fullPathForFilename(filename);

FILE *pFile = fopen(filePath.c_str(),"wb+");

if(!pFile)
{

log("save to file error::%s", filename.c_str());

return;
}

fputs(str.c_str(),pFile);

fclose(pFile);

log("save to file success::%s", filename.c_str());
}

void
JGUtil::readJson(JsonBox::Value &json,const
std::string filename) {

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JGUtil::copyData(filename.c_str());
std::string s_filepath = CCFileUtils::sharedFileUtils()->getWritablePath() + filename;
json.loadFromFile(s_filepath.c_str());

#else

std::string s_filepath =
FileUtils::getInstance()->fullPathForFilename(filename);

log("claudis filename = %s",s_filepath.c_str());
json.loadFromFile(s_filepath.c_str());

//log("claudis %s",json.getString().c_str());

#endif
}

bool
JGUtil::readJson(rapidjson::Document &doc,const
std::string filename) {

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JGUtil::copyData(filename.c_str());
std::string s_filepath = CCFileUtils::sharedFileUtils()->getWritablePath() + filename;

ssize_t size;

unsigned char *ch = FileUtils::getInstance()->getFileData(s_filepath,"rw",&size);
std::string data = std::string((const
char*)ch,size);
doc.Parse<0>(data.c_str());///<通过Parse方法将Json数据解析出来

if(doc.HasParseError())
{
CCLOG("GetParseError%s\n",doc.GetParseError());

return
false;
}

return
true;

// json.readJson(json, s_filepath.c_str());

#else

ssize_t size;

std::string s_filepath =
FileUtils::getInstance()->fullPathForFilename(filename);

unsigned char *ch =
FileUtils::getInstance()->getFileData(s_filepath,"rw",&size);

std::string data =
std::string((const
char*)ch,size);

doc.Parse<0>(data.c_str());///<通过Parse方法将Json数据解析出来

if(doc.HasParseError())
{

CCLOG("GetParseError%s\n",doc.GetParseError());

return
false;
}

return
true;

#endif
}

ClippingNode*
JGUtil::ccDrawRoundRect(cocos2d::Sprite *bgSprite,
cocos2d::Vec2 origin,
cocos2d::Vec2 destination,
float radius, unsigned
int segments){

Sprite *thisbgSprite = bgSprite;

ClippingNode* pClip =
ClippingNode::create();

pClip->setInverted(false);//设置是否反向,将决定画出来的圆是透明的还是黑色的

// this->addChild(pClip);
pClip->setAnchorPoint(Point(0,
0));
pClip->setPosition(-7, -7);

//算出1/4圆

const float coef =
0.5f * (float)M_PI / segments;

Point * vertices =
new Point[segments +
1];

Point * thisVertices = vertices;

for (unsigned
int i = 0; i <= segments; ++i, ++thisVertices)
{

float rads = (segments - i)*coef;
thisVertices->x = (int)(radius *
sinf(rads));
thisVertices->y = (int)(radius *
cosf(rads));
}

//

Point tagCenter;

float minX = MIN(origin.x, destination.x);

float maxX = MAX(origin.x, destination.x);

float minY = MIN(origin.y, destination.y);

float maxY = MAX(origin.y, destination.y);

unsigned int dwPolygonPtMax = (segments +
1) * 4;

Point * pPolygonPtArr =
new Point[dwPolygonPtMax];

Point * thisPolygonPt = pPolygonPtArr;

int aa = 0;

//左上角
tagCenter.x = minX + radius;
tagCenter.y = maxY - radius;
thisVertices = vertices;

for (unsigned
int i = 0; i <= segments; ++i, ++thisPolygonPt, ++thisVertices)
{
thisPolygonPt->x = tagCenter.x - thisVertices->x;
thisPolygonPt->y = tagCenter.y + thisVertices->y;
++aa;
}

//右上角
tagCenter.x = maxX - radius;
tagCenter.y = maxY - radius;
thisVertices = vertices + segments;

for (unsigned
int i = 0; i <= segments; ++i, ++thisPolygonPt, --thisVertices)
{
thisPolygonPt->x = tagCenter.x + thisVertices->x;
thisPolygonPt->y = tagCenter.y + thisVertices->y;
++aa;
}

//右下角
tagCenter.x = maxX - radius;
tagCenter.y = minY + radius;
thisVertices = vertices;

for (unsigned
int i = 0; i <= segments; ++i, ++thisPolygonPt, ++thisVertices)
{
thisPolygonPt->x = tagCenter.x + thisVertices->x;
thisPolygonPt->y = tagCenter.y - thisVertices->y;
++aa;
}

//左下角
tagCenter.x = minX + radius;
tagCenter.y = minY + radius;
thisVertices = vertices + segments;

for (unsigned
int i = 0; i <= segments; ++i, ++thisPolygonPt, --thisVertices)
{
thisPolygonPt->x = tagCenter.x - thisVertices->x;
thisPolygonPt->y = tagCenter.y - thisVertices->y;

// log("%f , %f", thisPolygonPt->x, thisPolygonPt->y);
++aa;
}

//设置参数

static
Color4F red(1,
0, 0,
1);//顶点颜色设置为红色,参数是R,G,B,透明度

//注意不要将pStencil addChild

DrawNode *pStencil =
DrawNode::create();
pStencil->drawPolygon(pPolygonPtArr, dwPolygonPtMax, red,
0, red);//绘制这个多边形

pStencil->setPosition(Point(0,
0));

pClip->setStencil(pStencil);

pClip->addChild(thisbgSprite,
1);
pClip->setContentSize(thisbgSprite->getContentSize());

CC_SAFE_DELETE_ARRAY(vertices);

CC_SAFE_DELETE_ARRAY(pPolygonPtArr);

return pClip;
}

void
JGUtil::saveDataToJson(JsonBox::Value &json,const
std::string filename) {

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

std::string s_filepath = CCFileUtils::sharedFileUtils()->getWritablePath() + filename;
json.writeToFile(s_filepath);

#else

std::string s_filepath =
FileUtils::getInstance()->fullPathForFilename(filename);
json.writeToFile(s_filepath);

#endif
}

void
JGUtil::saveDataToJson(rapidjson::Document &json,const
std::string filename) {

rapidjson::StringBuffer buffer;

rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Accept(writer);

#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

//system("delE:\cocos2d-x-3.2rc0\tests\cpp-empty-test\Resources\test.josn");///<先将文件删除掉---之前重这个文件读取数据,因此确保这个文件存在了
std::string s_filepath = CCFileUtils::sharedFileUtils()->getWritablePath() + filename;
FILE *file = fopen(s_filepath.c_str(),"wb");

if(file)
{
fputs(buffer.GetString(),file);
fclose(file);
}

#else //if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

std::string s_filepath =
FileUtils::getInstance()->fullPathForFilename(filename);

//log("claudis ############## %s",s_filepath.c_str());

FILE *file= fopen(s_filepath.c_str(),"wb");

if(file)
{

fputs(buffer.GetString(),file);

fclose(file);
}

#endif
}

wchar_t*
JGUtil::MBCS2Unicode(wchar_t * buff,
const char * str)
{

wchar_t *wp = buff;

char * p = (char *)str;

while(*p)
{

if(*p & 0x80)
{
*wp = *(wchar_t *)p;
p++;
}

else
{
*wp = (wchar_t) *p;
}
wp++;
p++;
}
*wp =
0x0000;

return buff;
}

char*
JGUtil::Unicode2MBCS(char* buff,
const wchar_t* str)
{

wchar_t * wp = (wchar_t *)str;

char * p = buff, * tmp;

while(*wp){
tmp = (char *)wp;

if(*wp & 0xFF00){
*p = *tmp;
p++;tmp++;
*p = *tmp;
p++;
}

else
{
*p = *tmp;
p++;
}
wp++;
}
*p =
0x00;

return buff;
}

std::wstring
JGUtil::str2wstr(std::string str)
{

size_t len = str.size();

wchar_t * b = (wchar_t *)malloc((len+1)*sizeof(wchar_t));

MBCS2Unicode(b,str.c_str());

std::wstring r(b);

free(b);

return r;
}

std::string
JGUtil::wstr2str(std::wstring wstr)
{

size_t len = wstr.size();

char * b = (char *)malloc((2*len+1)*sizeof(char));

Unicode2MBCS(b,wstr.c_str());

std::string r(b);

free(b);

return r;
}

int
JGUtil::wputs(std::wstring wstr)
{

wputs(wstr.c_str());

return
0;
}

int
JGUtil::wputs(const
wchar_t * wstr)
{

int len = wcslen(wstr);

char * buff = (char *)malloc((len *
2 + 1)*sizeof(char));

Unicode2MBCS(buff,wstr);

printf("%s",buff);

free(buff);

return
0;
}

wchar_t*
JGUtil::UTF8ToUnicode(const
char* str)
{

// int textlen;

// wchar_t* result;

// textlen = MultiByteToWideChar( CP_UTF8, 0, str,-1, NULL,0 );

// result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));

// memset(result,0,(textlen+1)*sizeof(wchar_t));

// MultiByteToWideChar(CP_UTF8, 0,str,-1,(LPWSTR)result,textlen );

// return result;
}

char*
JGUtil::UnicodeToUTF8(const
wchar_t* str)
{

// char* result;

// int textlen;

// textlen = WideCharToMultiByte( CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL );

// result =(char *)malloc((textlen+1)*sizeof(char));

// memset(result, 0, sizeof(char) * ( textlen + 1 ) );

// WideCharToMultiByte( CP_UTF8, 0, str, -1, result, textlen, NULL, NULL );

// return result;
}

std::string&
JGUtil::replace_all(std::string& str,const
std::string& old_value,const
std::string& new_value)
{

while(true) {

std::string::size_type pos(0);

if( (pos=str.find(old_value))!=string::npos )
str.replace(pos,old_value.length(),new_value);

else break;
}

return str;
}
std::string&
JGUtil::replace_all_distinct(std::string& str,const
std::string& old_value,const
std::string& new_value)
{

for(string::size_type pos(0); pos!=string::npos;
pos+=new_value.length()) {

if( (pos=str.find(old_value,pos))!=string::npos )
str.replace(pos,old_value.length(),new_value);

else break;
}

return str;
}

int
JGUtil::getUtf8CNLength(const
std::string &src,
unsigned size )
{

size_t i = 0;

int count = 0;

for ( ;i < src.length(); )
{

int inc = utf8_step ( src[i] );

if ( 0 >= inc )
break;

i += inc;

if(inc > 1)
count ++;

if ( size <= i ) break;
}

return count;
}

int
JGUtil::getUtf8Length(const
std::string &src,
unsigned size )
{

size_t i = 0;

int count = 0;

for ( ;i < src.length(); )
{

int inc = utf8_step ( src[i] );

if ( 0 >= inc )
break;

i += inc;

count ++;

if ( size <= i ) break;
}

return count;
}

std::string
JGUtil::truncUtf8 (
const std::string& src,
unsigned size )
{

if ( src.length() <= size )
return src;

int utf8CNLen = getUtf8CNLength(src, size);

if(utf8CNLen > 2)

{//有中文时直接加大些,中文显示的宽度跟英文的有差别
size =
MIN(size + ceil(utf8CNLen*2/3) +
1, (int)src.length());
}

size_t i = 0;

for ( ;i < src.length(); )
{

int inc = utf8_step ( src[i] );

if ( 0 >= inc )
break;

i += inc;

if ( size <= i ) break;
}

std::string str = src.substr (
0, i );

return str;
}

int
JGUtil::utf8_step(char b0)
{

if ( (b0 & 0x80) ==
0 )

return 1;

if ((b0 & 0xC0) !=
0xC0)

return 0;

if ((b0 & 0xE0) ==
0xC0)

return 2;

if ((b0 & 0xF0) ==
0xE0)

return 3;

if ((b0 & 0xF8) ==
0xF0)

return 4;

return
0;
};

std::string
JGUtil::getYearMonthDay()
{

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

struct timeval now;

struct tm* time;

gettimeofday(&now,
NULL);

time =
localtime(&now.tv_sec);

int year = time->tm_year +
1900;

// log("year = %d",year);

char date[32] = {0};

sprintf(date, "%d-%02d-%02d",(int)time->tm_year +
1900,(int)time->tm_mon +
1,(int)time->tm_mday);

// log("%s",date);

return StringUtils::format("%s",date);

#endif

#if ( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )

struct tm* tm;
time_t timep;
time(timep);

tm = localtime(&timep);

char date[32] = {0};
sprintf(date,
"%d-%02d-%02d",(int)time->tm_year +
1900,(int)time->tm_mon +
1,(int)time->tm_mday);

// log("%s",date);

return StringUtils::format("%s",date);

#endif
}

int
JGUtil::getWeekday()
{

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

struct timeval now;

struct tm* time;

gettimeofday(&now,
NULL);
time =
localtime(&now.tv_sec);

return time->tm_wday;

#endif

#if ( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )

struct tm* tm;
time_t timep;
time(timep);
tm = localtime(&timep);

return time->tm_wday;

#else

return
0;

#endif
}

std::string
JGUtil::getHourMinute()
{

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

struct timeval now;

struct tm* time;

gettimeofday(&now,
NULL);
time =
localtime(&now.tv_sec);

int year = time->tm_year +
1900;

char date[32] = {0};

sprintf(date, "%02d:%02d",(int)time->tm_hour,(int)time->tm_min);

return StringUtils::format("%s",date);

#endif

#if ( CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 )

struct tm* tm;
time_t timep;
time(timep);
tm = localtime(&timep);

char date[32] = {0};
sprintf(date,
"%02d:%02d",(int)time->tm_hour,(int)time->tm_min);

return StringUtils::format("%s",date);

#endif

}

std::string
JGUtil::getNumberStr(int count)
{

float wan = count*1.0f/10000;

float yi = wan/10000;

// std::string str = "";

// std::stringstream stream;

// if(yi > 0)

// {

// stream<<yi;

// str += stream.str() + "亿";

// }

// else if(wan > 0)

// {

// stream<<wan;

// str += stream.str() + "万";

// }else

// {

// stream<<count;

// str += stream.str();

// }

char * data = NULL;
data = (char *)malloc(20);

if(yi >= 1)
{

sprintf(data, "%.2f亿", yi);
}else
if(wan >= 1)
{

sprintf(data, "%.2f万", wan);
}else{

sprintf(data, "%d", count);
}

std::string str =
std::string(data);

free(data);

return str;
}

//从秒转换为时分秒
std::string
JGUtil::secondTohms(int m)
{

int shi,fen,miao;

std::string result =
"";
shi = m/3600;

fen = m/60%60;
miao = m%60;
result =
StringUtils::format("%02d:%02d:%02d",shi,fen,miao);

return result;
}

std::string
JGUtil::getCNNumber(std::string &number)
{

std::string ret =
"";

int totalLen = (int)number.length();

for(int i =
0; i < totalLen; i++)
{

std::string tempStr =
getCharCNNumber(number.at(i));

int delta = totalLen - i;
ret += tempStr;

if(delta == 5)
ret +=
"万";

else if(delta ==
4)
ret +=
"千";

else if(delta ==
3)
ret +=
"百";

else if(delta ==
2)
ret +=
"十";
}

return ret;
}

std::string
JGUtil::getCharCNNumber(char cnum)
{

std::string ret =
"";

if(cnum == '1')
{
ret =
"一";
}else
if(cnum == '2')
{
ret =
"二";
}else
if(cnum == '3')
{
ret =
"三";
}

else if(cnum ==
'4')
{
ret =
"四";
}

else if(cnum ==
'5')
{
ret =
"五";
}

else if(cnum ==
'6')
{
ret =
"六";
}

else if(cnum ==
'7')
{
ret =
"七";
}

else if(cnum ==
'8')
{
ret =
"八";
}

else if(cnum ==
'9')
{
ret =
"九";
}

return ret;
}

int64_t
JGUtil::getSystemTime()
{

struct timeval tv;

gettimeofday(&tv,NULL);

return ((int64_t)tv.tv_sec) *
1000 + tv.tv_usec /
1000;
}

long
long JGUtil::getSystemTimeSec()
{

timeval time;

gettimeofday(&time,
nullptr);

return ((long
long)time.tv_sec);
}

struct
tm* JGUtil::getTimeInfo(long duration)
{

time_t time_sec =
time_t(duration);

struct tm * t;

t =
localtime(&time_sec);

//int nMinute = tm->tm_min;

//int nSecond = tm->tm_sec;

//int nHour = tm->tm_hour;

//int day = tm->tm_mday;

//int month = tm->tm_mon;

return t;
}

bool
JGUtil::isMonthEnd(int year,
int month, int day)
{

switch(month) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:

if (day == 31) {

return true;
}

return false;

case 4:

case 6:

case 9:

case 11:

if (day == 30) {

return true;
}

return false;

case 2:

if (isLeapYear(year) && day ==
29) {

return true;
}

else if (!isLeapYear(year) && day ==
28) {

return true;
}

return false;

default:

return false;
}
}

bool
JGUtil::isLeapYear(int year)
{

if(year%4 ==
0 && (year%100 !=0 || year%400==0))

return true;

return
false;
}

int
JGUtil::getDaysInMonth(int year ,
int month)
{

int days;

for(int i =
1; i < month; i++)
{

switch(month) {

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:
days +=
31;

break;

case 4:

case 6:

case 9:

case 11:
days +=
30;

break;

case 2:

if (isLeapYear(year)) {
days +=
29;//闰年
}

else if (!isLeapYear(year)) {
days +=
28;
}

break;
}
}

return days;
}

int
JGUtil::getDaysOfMonthInYear(int year ,int month)
{

int days=30;

switch(month)
{

case 1:

case 3:

case 5:

case 7:

case 8:

case 10:

case 12:
days =
31;

break;

case 4:

case 6:

case 9:

case 11:
days =
30;

break;

case 2:

if (isLeapYear(year)) {
days =
29;//闰年
}

else if (!isLeapYear(year)) {
days =
28;
}

break;
}

return days;
}

string JGUtil::trim(string &s)
{

if(s.empty())
{

return s;
}

s.erase(0,s.find_first_not_of(" "));

s.erase(s.find_last_not_of(" ") +
1);

return s;
}

unsigned char
JGUtil::ToHex(unsigned
char x)
{

return x > 9 ? x +
55 : x + 48;
}

unsigned char
JGUtil::FromHex(unsigned
char x)
{

unsigned
char y;

if (x >= 'A' && x <=
'Z') y = x - 'A' +
10;

else if (x >=
'a' && x <= 'z') y = x -
'a' + 10;

else if (x >=
'0' && x <= '9') y = x -
'0';

else assert(0);

return y;
}

//url编码
std::string
JGUtil::UrlEncode(const
std::string& str)
{

std::string strTemp =
"";

size_t length = str.length();

for (size_t i =
0; i < length; i++)
{

if (isalnum((unsigned
char)str[i]) ||
(str[i] ==
'-') ||
(str[i] ==
'_') ||
(str[i] ==
'.') ||
(str[i] ==
'~'))
strTemp += str[i];

else if (str[i] ==
' ')
strTemp +=
"+";

else
{
strTemp +=
'%';
strTemp +=
ToHex((unsigned
char)str[i] >>
4);
strTemp +=
ToHex((unsigned
char)str[i] %
16);
}
}

return strTemp;
}

//url解码
std::string
JGUtil::UrlDecode(const
std::string& str)
{

std::string strTemp =
"";

size_t length = str.length();

for (size_t i =
0; i < length; i++)
{

if (str[i] ==
'+') strTemp += ' ';

else if (str[i] ==
'%')
{

assert(i + 2 < length);

unsigned char high =
FromHex((unsigned
char)str[++i]);

unsigned char low =
FromHex((unsigned
char)str[++i]);
strTemp += high*16 + low;
}

else strTemp += str[i];
}

return strTemp;
}

int
JGUtil::getRandomInt(int min,int max)
{

float i = CCRANDOM_0_1()*(max-min+1)+min;

return (int)i;

}

std::string
JGUtil::getNewDate(int year,int month,int day,int diffDays)
{

int mYear,mMonth,mDay;

int normalMonthDays[13] = {0,
31, 28,
31, 30, 31,
30, 31,
31, 30, 31,
30, 31};

mYear = year;
mMonth = month;
mDay = day;

//1.get years (days >=366 or 365)

int daysAyear = 365;

if(isLeapYear(mYear))

{//if leap year
daysAyear =
366;
}

while(diffDays/daysAyear)
{
diffDays = diffDays - daysAyear;
mYear ++;

if(isLeapYear(mYear))
{
daysAyear =
366;
}
}

//2.get months (days < 366 or 365)

if(isLeapYear(mYear))
{
normalMonthDays[2]=29;
}

while(diffDays/normalMonthDays[mMonth])
{
diffDays = diffDays - normalMonthDays[mMonth];
mMonth++;

if(mMonth >= 13)
{
mYear++;

if(isLeapYear(mYear))
{
normalMonthDays[2]=29;
}
mMonth = mMonth%12;
}
}

//3.get days

if(isLeapYear(mYear))
{
normalMonthDays[2]=29;
}

if(diffDays + mDay <= normalMonthDays[mMonth])
mDay = diffDays + mDay;

else
{
mDay = diffDays + mDay - normalMonthDays[mMonth];
mMonth++;

if(mMonth > 12)
{
mYear++;
mMonth = mMonth%12;
}
}

char date[32] = {0};

sprintf(date, "%d-%02d-%02d",mYear,mMonth,mDay);

return StringUtils::format("%s",date);
}

std::string
JGUtil::getNewString(std::string str,int startP,int no,std::string
reStr)
{

string strTemp = "";
strTemp = str.replace(startP, no, reStr);

return strTemp;
}

Node*
JGUtil::findNodeByName(Node* root,
const std::string& name)
{

if (!root)
{

return
nullptr;
}

if (root->getName() == name)
{

return root;
}

const auto& arrayRootChildren = root->getChildren();

for (auto& subWidget : arrayRootChildren)
{

Node* child = dynamic_cast<Node*>(subWidget);

if (child)
{

Node* res = findNodeByName(child,name);

if (res != nullptr)
{

return res;
}
}
}

return
nullptr;
}

std::string
JGUtil::repleceByChar(std::string str,char finChar,char repChar)
{

int len = (int)str.length();

for (int i=0;i<len;i++)
{

if (str[i]==finChar)
{
str[i]=repChar;
}
}

return trim(str);
}

cocos2d::Color4B
JGUtil::int2ccc3(unsigned
long color)
{

Color4B ret;
ret.r = (color&0xffffffff)>>24;
ret.g = (color&0xffffff)>>16;
ret.b = (color&0xffff)>>8;
ret.a = color&0xff;

return ret;
}

string
JGUtil::getWeekday(int year,int month,int day)//取日期是星期几
{

string Weekday[7] =
{

"星期日","星期一","星期二",

"星期三","星期四","星期五",

"星期六"
};

int Month[12] =
{

31,28,31,30,31,30,31,31,20,31,30,31
};

int w,c,y,m;

if(year > 10000 || year <=
1582)
{
year =
2015;
}

if( (year % 4 ==
0 && year % 100 !=
0) || (year % 400 ==
0) ) //判断闰年的情况
{
Month[1] =
29;
}

if(month > 12 || month <=
0)
{
month =
1;
}

if(day > Month[month -
1] || day <= 0)
{
day =
1;
}

//使用蔡勒(Zeller)公式计算星期几,1582年后有效

if( month <= 2)
//1,2 月看做上一年的 13,14

{
c = (year -
1) / 100;
y = (year -
1) % 100;
m = month +
12;
}

else
{
c = year /
100;
y = year %
100;
m = month;
}
w = y + y /4 + c /
4 - 2 * c +
26 *(m + 1) /
10 + day -1;

if(w >= 7)
{
w = w %
7;
}

else
//被除数为负数的情况
{

while(w < 0)
{
w = w +
7;
}
}

if( w > 6) w =
0;//星期天,

return Weekday[w];
}

std::vector<std::string>
JGUtil::getFilePathAtVec(std::string filePath)
{

std::vector<std::string> path_vec;

std::vector<std::string> temp_vec;

DIR *dp;

struct dirent *entry;

struct stat statbuf;

bool isDir = true;

if((dp=opendir(filePath.c_str()))==NULL)
{

fprintf(stderr,"cannot open %s",filePath.c_str());
isDir =
false;
}

if (isDir) {

while((entry=readdir(dp))!=NULL)
{

stat(entry->d_name,&statbuf);

if(strcmp(entry->d_name,".") !=
0 && strcmp(entry->d_name,"..") !=
0)
{

//过滤掉隐藏文件

if(entry->d_name[0]!='.')
{

if (FileUtils::getInstance()->isDirectoryExist(filePath+entry->d_name))
{
path_vec.push_back(StringUtils::format("%s",entry->d_name));
}

else
{
temp_vec.push_back(StringUtils::format("%s",entry->d_name));
}
}
}
}

for (int i =
0; i<temp_vec.size(); i ++)
{
path_vec.push_back(temp_vec[i]);
}
}

closedir(dp);

return path_vec;
}

std::string
JGUtil::getPicByFileName(std::string fileName,bool isCloudShare,bool isCloudDir)
{

std::string filePic =
"myJmgo/file_type_unknow.png";

bool isDirctory =false;/////是否是文件夹

if (isCloudShare) {
isDirctory =isCloudDir;
}else
{
isDirctory=FileUtils::getInstance()->isDirectoryExist(fileName);
}

if (isDirctory)
{
filePic =
"myJmgo/folder.png";
}

else
{

std::string lastName =
"";

if (isCloudShare)
{
lastName = fileName;/////是云分享,直接传后缀名,不用调用系统的api
}
else
{
lastName =
FileUtils::getInstance()->getFileExtension(fileName);
}

if (JGUtil::compareNoCase(lastName,".doc"))
{

filePic = "myJmgo/file_type_word.png";
}

else if (JGUtil::compareNoCase(lastName,
".bmp") || JGUtil::compareNoCase(lastName,".jpg")||
JGUtil::compareNoCase(lastName,".jpeg")||JGUtil::compareNoCase(lastName,".png")||JGUtil::compareNoCase(lastName,".gif"))
{

filePic = "myJmgo/file_type_pic.png";
}

else if (JGUtil::compareNoCase(lastName,".apk"))
{

filePic = "myJmgo/file_type_apk.png";
}

else if (JGUtil::compareNoCase(lastName,".excel"))
{

filePic = "myJmgo/file_type_excel.png";
}

else if (JGUtil::compareNoCase(lastName,".ppt"))
{

filePic = "myJmgo/file_type_ppt.png";
}

else if (JGUtil::compareNoCase(lastName,".flac")||
JGUtil::compareNoCase(lastName,".ape")||JGUtil::compareNoCase(lastName,".m3u")||
JGUtil::compareNoCase(lastName,".m4a")||JGUtil::compareNoCase(lastName,".m4b")||JGUtil::compareNoCase(lastName,".m4p")||JGUtil::compareNoCase(lastName,".mp1")||JGUtil::compareNoCase(lastName,".mp2")||JGUtil::compareNoCase(lastName,".mp3")
||JGUtil::compareNoCase(lastName,".mpga")||JGUtil::compareNoCase(lastName,".ogg")||JGUtil::compareNoCase(lastName,".wav")||JGUtil::compareNoCase(lastName,".wma")||JGUtil::compareNoCase(lastName,".aac")||JGUtil::compareNoCase(lastName,".ac3")||JGUtil::compareNoCase(lastName,".amr")||JGUtil::compareNoCase(lastName,".dts")||JGUtil::compareNoCase(lastName,".ra"))
{

filePic = "myJmgo/file_type_music.png";
}

else if (JGUtil::compareNoCase(lastName,".avi")||
JGUtil::compareNoCase(lastName,".mpg")||
JGUtil::compareNoCase(lastName,".dat")||
JGUtil::compareNoCase(lastName,".vob") ||
JGUtil::compareNoCase(lastName,".div")||JGUtil::compareNoCase(lastName,".mov")
|| JGUtil::compareNoCase(lastName,".mkv")||
JGUtil::compareNoCase(lastName,".rm") ||
JGUtil::compareNoCase(lastName,".3gp") ||
JGUtil::compareNoCase(lastName,".m4u")
||
JGUtil::compareNoCase(lastName,".rmvb")||
JGUtil::compareNoCase(lastName,".mp4") ||
JGUtil::compareNoCase(lastName,".mjpeg") ||
JGUtil::compareNoCase(lastName,".ts") ||JGUtil::compareNoCase(lastName,".m2ts")
|| JGUtil::compareNoCase(lastName,".trp") ||JGUtil::compareNoCase(lastName,".wmv")||JGUtil::compareNoCase(lastName,".flv")
||JGUtil::compareNoCase(lastName,".asf")||
JGUtil::compareNoCase(lastName,".m4v")||JGUtil::compareNoCase(lastName,".mpe")||JGUtil::compareNoCase(lastName,".mpeg")||
JGUtil::compareNoCase(lastName,".mpg4")||
JGUtil::compareNoCase(lastName,".rmvb"))
{

filePic = "myJmgo/file_type_video.png";
}
}

return filePic;
}

bool
JGUtil::checkFileIsFolder(std::string filePath)
{

bool isDir = false;

if (FileUtils::getInstance()->isDirectoryExist(filePath))
{
isDir =
true;
}

return isDir;
}

bool
JGUtil::deleteFileOrFolder(std::string filePath)
{

bool isSuccess = false;

if (FileUtils::getInstance()->isDirectoryExist(filePath))
{

if (FileUtils::getInstance()->removeDirectory(filePath+"/"))
{
isSuccess =
true;
}

else
{
isSuccess =
false;
}
}

else if(FileUtils::getInstance()->isFileExist(filePath))
{

if (FileUtils::getInstance()->removeFile(filePath))
{
isSuccess =
true;
}

else
{
isSuccess =
false;
}
}

return isSuccess;
}

int
JGUtil::stoi(const
std::string& value)
{

// Android NDK 10 doesn't support std::stoi a/ std::stoul

#if CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID

return std::stoi(value);

#else

return atoi(value.c_str());

#endif
}

std::string
JGUtil::timeToDate(long times)
{

struct tm *l=localtime(×);

char buf[128];

snprintf(buf,sizeof(buf),"%04d-%02d-%02d %02d:%02d:%02d",l->tm_year+1900,l->tm_mon+1,l->tm_mday,l->tm_hour,l->tm_min,l->tm_sec);

string s(buf);

return StringUtils::format("%s",s.c_str());
}

long
JGUtil::getMondayTime(string strData)
{

std::string::size_type pos;

std::vector<std::string> result;

string pattern = "-";
strData += pattern;//扩展字符串以方便操作

size_t size = strData.size();

for(int i =
0; i< size; i++)
{
pos = strData.find(pattern,i);

if(pos < size)
{

std::string s = strData.substr(i,pos - i);
result.push_back(s);
i = (int)(pos + pattern.size()) -
1;
}
}

if(result.size() !=
3)
{

return 0;
}

int iYear = JGUtil::stoi(result.at(0)) -
1900;

int iMon = JGUtil::stoi(result.at(1)) -
1;

int iDay = JGUtil::stoi(result.at(2));

struct tm t;

time_t t_of_day;
t.tm_year = iYear;
t.tm_mon = iMon;
t.tm_mday = iDay;
t.tm_hour =
0;
t.tm_min =
0;
t.tm_sec =
0;
t.tm_isdst =
0;
t_of_day =
mktime(&t);

struct tm *pTmp =localtime(&t_of_day);

int day;

int week = pTmp->tm_wday;

//log("weekday =========%d",week);

if(week==0)
week =
7;
day = week -
1;
t_of_day -= day*24*3600;

return (long)t_of_day;

}

std::vector<std::string>
JGUtil::splitString(std::string str,std::string pattern)
{

std::vector<std::string> tempStr;

char *p;

char* name = new
char[strlen(str.c_str()) +
1];

sprintf(name, "%s", str.c_str());
p =
strtok(name,pattern.c_str());

while(p)
{

printf("%s\n",p);
tempStr.push_back(p);
p=strtok(NULL,pattern.c_str());
}

return tempStr;
}

std::string
JGUtil::getUrlLocalPath(string strUrl)
{

//获取FileUtiles对象

FileUtils *fileUtil=FileUtils::getInstance();

std::string fileName = strUrl;
fileName =
JGUtil::replace_all(fileName,
"/", "_");
fileName =
JGUtil::replace_all(fileName,
"\\", "_");

std::string localDir = fileUtil->getWritablePath()+"movie_ico/";

std::string localpath = fileUtil->fullPathForFilename(localDir+fileName);

if(!FileUtils::getInstance()->isFileExist(localpath))
{
localpath =
"";
}

return localpath;
}

std::string
JGUtil::getPathTooLang(const
std::string& src,
unsigned size)
{

if ( src.length() <= size )
return src;

int utf8CNLen = getUtf8CNLength(src, size);

if(utf8CNLen > 2)

{//有中文时直接加大些,中文显示的宽度跟英文的有差别
size =
MIN(size, size + ceil(utf8CNLen*2/3) +
1);
}

size_t i = 0;

for ( ;i < src.length(); )
{

int inc = utf8_step ( src[i] );

if ( 0 >= inc )
break;

i += inc;

if ( size <= i ) break;
}

// log("1364====%s",src.c_str());

std::string str = src.substr (0,i);

// log("1366====%s",str.c_str());

int pathLen1 = (int)str.length();

std::string str1 = src.substr (pathLen1,src.length());

// log("1370====%s",str1.c_str());

return "..."+str1;
}

// string转小写
std::string
JGUtil::strToLower(std::string str)
{

std::string strTmp = str;

transform(strTmp.begin(), strTmp.end(), strTmp.begin(),
towupper);

return strTmp;
}

// string.compareNoCase:不区分大小写
bool
JGUtil::compareNoCase(std::string strA,const
std::string strB)
{

string str1 = strToLower(strA);

string str2 = strToLower(strB);

return (str1 == str2);
}

void
JGUtil::removeAllStudioTouchEvent(Node* node){

for(auto item : node->getChildren()){

cocos2d::ui::Widget* w =
dynamic_cast<cocos2d::ui::Widget*>(item);

if(w && w->isTouchEnabled()){
w->setTouchEnabled(false);
}

Node* n = dynamic_cast<Node*>(item);

if(n){

removeAllStudioTouchEvent(n);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: