cocos2dx3.X uiimage 转 texture2d  或者 image 失败

在尝试将UIImage转换为cocos2d-x的Texture2D或Image时遇到错误,报空指针。尝试了多种网络上的转换方法,但都以失败告终。错误出现在void* data转换为unsighe char* data的过程中。代码示例显示了两种常见的转换失败情况,均在初始化Texture2D时出错。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   今天试了网络上各种流行的转法,最终结果都是失败告终。
在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. " );
       
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值