Search code examples
iphonequartz-2d

Getting uiimage from a rotated calayeer


I'm trying to get an uiimage from a calayer that I had previously rotated:

//Creates the rotation affine transform
m_transformada = CGAffineTransformIdentity;
m_transformada = CGAffineTransformRotate(m_transformada, M_PI / 4);
// Apply the affine transform to a UIVIewImage object
m_PhotoView.transform = m_transformada;

// Get's the UIImage from the UIViewImage
UIGraphicsBeginImageContext([m_PhotoView.layer frame].size);
[m_PhotoView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

The outputImage is not rotated... anyone knows why? Thanks,


Solution

  • The transform on the layer affects its geometry in its superlayer, not the layer itself.

    Something like this will work (this meant to be mixed in and/or otherwise adapted):

    - (UIImage*)renderToImageRotated:(float)scale {
      float tx = self.frame.size.width;
      float ty = self.frame.size.height;
      CGSize size = CGSizeMake(self.frame.size.height, self.frame.size.width);
      UIGraphicsBeginImageContextWithOptions(size, NO, scale);
      CGContextRef c = UIGraphicsGetCurrentContext();
      CGContextTranslateCTM (c, ty/2, tx/2);
      CGContextRotateCTM(c, M_PI/2);
      CGContextTranslateCTM (c, -tx/2, -ty/2);
      [self.layer renderInContext:c];
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();  
      return image;
    }