0

I am new in opengl es 2.0 development. The UIImage I got from screenshot looks good on non-retina devices (iphone 4 and ipad), but when I got screenshot from retina devices it seems enlarged. Here is the code I used.

-(UIImage *) glToUIImage {

  CGSize size = self.view.frame.size;

  // the reason I set the height and width up-side-down is because my 
  // screenshot captured in landscape mode.
  int image_height = (int)size.width; 
  int image_width  = (int)size.height;

  NSInteger myDataLength = image_width * image_height * 4;

  // allocate array and read pixels into it.
  GLubyte *buffer = (GLubyte *) malloc(myDataLength);
  glReadPixels(0, 0, image_width, image_height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

  // gl renders "upside down" so swap top to bottom into new array.
  // there's gotta be a better way, but this works.
  GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
  for(int y = 0; y < image_height; y++)
 {
    for(int x = 0; x < image_width * 4; x++)
    {
        buffer2[(image_height - 1 - y) * image_width * 4 + x] = buffer[y * 4 * image_width + x];
    }
}

  // make data provider with data.
  CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

  // prep the ingredients
  int bitsPerComponent = 8;
  int bitsPerPixel = 32;
  int bytesPerRow = 4 * image_width;
  CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
  CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
  CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

  // make the cgimage
  CGImageRef imageRef = CGImageCreate(image_width, image_height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

  // then make the uiimage from that
  UIImage *myImage = [UIImage imageWithCGImage:imageRef];

  return myImage;
}

 // screenshot function, combined my opengl image with background image and
 // saved into Photos.
 -(UIImage*)screenshot
 {
  UIImage *image = [self glToUIImage];

  CGRect pos = CGRectMake(0, 0, image.size.width, image.size.height);
  UIGraphicsBeginImageContext(image.size);

  [image drawInRect:pos];
  [self.background.image drawInRect:pos];
  UIImage* final = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  // final picture I saved into Photos.
  return final;
}

Function is working, but the opengl image only shows part in retina devices, how to solve this problem. Thanks !!!

4

1 回答 1

1

您的代码假定视图大小等于像素,但事实并非如此。是积分。您需要转换为每个设备的实际像素大小。UIScreen 有一个 scale 属性。

于 2013-09-10T00:41:54.550 回答