Convert an UIImage in a texture

后端 未结 3 883
闹比i
闹比i 2020-12-03 06:27

In my opengl project I need to convert an UIImage in texture; what\'s the way to do it? Can you help me?

3条回答
  •  情深已故
    2020-12-03 07:01

    I haven't test the following but i will decompose the conversion in 3 steps:

    1. Extract info for your image:

      UIImage* image = [UIImage imageNamed:@"imageToApplyAsATexture.png"];
      CGImageRef imageRef = [image CGImage];
      int width = CGImageGetWidth(imageRef);
      int height = CGImageGetHeight(imageRef);
      
    2. Allocate a textureData with the above properties:

      GLubyte* textureData = (GLubyte *)malloc(width * height * 4); // if 4 components per pixel (RGBA)
      
      CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
      NSUInteger bytesPerPixel = 4;
      NSUInteger bytesPerRow = bytesPerPixel * width;
      NSUInteger bitsPerComponent = 8;  
      CGContextRef context = CGBitmapContextCreate(textureData, width, height,
                                                   bitsPerComponent, bytesPerRow, colorSpace,
                                                   kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
      
      CGColorSpaceRelease(colorSpace);
      
      CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
      CGContextRelease(context);
      
    3. Set-up your texture:

      GLuint textureID;    
      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glGenTextures(1, &textureID);
      
      glBindTexture(GL_TEXTURE_2D, textureID);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
      

    EDIT:

    Read this tut; everything is explained from the conversion of one image to a texture and applying a texture in an iOS environment.

提交回复
热议问题