您的位置:首页 > 移动开发 > Cocos引擎

cocos2dx3.X uiimage 转 texture2d  或者 image 失败

2017-07-13 22:20 363 查看
   今天试了网络上各种流行的转法,最终结果都是失败告终。
在void* data类型转到unsighe char* data过程中报错,直接报空指针。

类似失败代码1:
//    uiimage


texture2d等的都会出现错误 

错误原因
未知
   
cocos2d::Texture2D
*texture =
new cocos2d::Texture2D();

   

    CGImageRef
imageRef = [(UIImage*)pImage
CGImage];

    NSUInteger
width = CGImageGetWidth(imageRef);

    NSUInteger
height = CGImageGetHeight(imageRef);

    CGColorSpaceRef
colorSpace =
CGColorSpaceCreateDeviceRGB();

    unsigned
char* rawData = (unsigned
char*)
calloc(height * width *
4,
sizeof(unsigned
char));

    NSUInteger
bytesPerPixel = 4;

    NSUInteger
bytesPerRow = bytesPerPixel * width;

    NSUInteger
bitsPerComponent = 8;

    CGContextRef
context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast
|
kCGBitmapByteOrder32Big);

    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context,
CGRectMake(0,
0, width, height), imageRef);

    CGContextRelease(context);

   

    if
(texture->initWithData(rawData, height * width *
4,
cocos2d::Texture2D::PixelFormat::RGBA8888,
(int)width, (int)height,
cocos2d::Size(width, height)))

    {

        if
(ROLE_MANAGER->saveImageForFileName(texture))
{

            CCLOG(" image success to save !~");

            texture->autorelease();

            flag = true;

        }

        else{

            CCLOG(" image fail to save !~");

           

        }

    }

    else{

        CCLOG("  uiimage transfrom is fail!~  init error. ");

       

    }

   

    if
(!flag)
        delete texture;

类似代码2:
cocos2d::Image
*image =
new(std::nothrow)
cocos2d::Image();

    cocos2d::Texture2D
*texture =
new cocos2d::Texture2D();

   

   
//    if (image->initWithRawData((unsigned char*)pData, pLength, pWidth, pHeight, 4)) {
//        if (ROLE_MANAGER->saveImageForFileName(image)) {

   

    if
(texture->initWithData(pData, pLength,
cocos2d::Texture2D::PixelFormat::RGBA8888,
pWidth, pHeight, cocos2d::Size(pWidth,
pHeight))) {

        if
(ROLE_MANAGER->saveImageForFileName(texture))
{

            CCLOG(" image success to save !~");

            image->autorelease();

            flag = true;

        }

        else{

            CCLOG(" image fail to save !~");

           

        }

    }

    else{

        CCLOG("  uiimage transfrom is fail!~  init error. ");

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