cocos2dx3.X uiimage 转 texture2d  或者 image 失败

来源:互联网 发布:nginx 配置本地目录 编辑:程序博客网 时间:2024/05/06 11:12
   今天试了网络上各种流行的转法,最终结果都是失败告终。
在void* data类型转到unsighe char* data过程中报错,直接报空指针。

类似失败代码1:
//    uiimage texture2d等的都会出现错误 错误原因 未知
   
cocos2d::Texture2D*texture = new cocos2d::Texture2D();
   
   
CGImageRef imageRef = [(UIImage*)pImageCGImage];
   
NSUInteger width = CGImageGetWidth(imageRef);
   
NSUInteger height = CGImageGetHeight(imageRef);
   
CGColorSpaceRefcolorSpace = CGColorSpaceCreateDeviceRGB();
   
unsigned char* rawData = (unsignedchar*)calloc(height * width *4,sizeof(unsignedchar));
   
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. ");
       
    }
原创粉丝点击