在保存为PNG格式之前,将新创建的iOS图像旋转90度

5

我已经阅读了很多与此相关的答案,但仍无法使其正常工作。

我有一个视图,用户可以在其中签名。它看起来像这样:http://d.pr/i/McuE

我可以成功地检索此图像并将其保存到文件系统中,但在保存之前需要将其旋转90度,以便签名从左到右读取。

// Grab the image
UIGraphicsBeginImageContext(self.signArea.bounds.size);
[self.signArea drawRect: self.signArea.bounds];
UIImage *signatureImage = UIGraphicsGetImageFromCurrentImageContext();

//-- ? -- Rotate the image (this doesn't work) -- ? --
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRotateCTM(context, M_PI_2);

UIGraphicsEndImageContext();

//Save the image as a PNG in Documents folder
[UIImagePNGRepresentation(signatureImage) writeToFile:[[PPHelpers documentsPath] stringByAppendingPathComponent:@"signature-temp.png"] atomically:YES];

如何在保存之前旋转图片?

感谢您的帮助。 我使用iOS 7 SDK上的Xcode 5。


在调用CGContextRotateCTM时,需要将角度转换为弧度。 - yurish
@yurish 我尝试使用radians(90),但出现了语法错误。 - Clifton Labrum
以下是我尝试过但没有成功的其他方法,主要是因为我对这些东西感到困惑。这是我应用程序中一个孤立的功能模块,而且我对图像处理还很陌生。 - Clifton Labrum
https://dev59.com/iWQn5IYBdhLWcg3wiHfl - Clifton Labrum
这是我在“旋转图像”下的代码:CGContextRef context = UIGraphicsGetCurrentContext(); CGContextRotateCTM(context, M_PI_2); - Clifton Labrum
显示剩余8条评论
1个回答

18

我最终使用该帖子上的其中一个答案成功解决了问题:如何将UIImage旋转90度?

我使用了这个方法:

- (UIImage *)imageRotatedByDegrees:(UIImage*)oldImage deg:(CGFloat)degrees{
  //Calculate the size of the rotated view's containing box for our drawing space
  UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,oldImage.size.width, oldImage.size.height)];
  CGAffineTransform t = CGAffineTransformMakeRotation(degrees * M_PI / 180);
  rotatedViewBox.transform = t;
  CGSize rotatedSize = rotatedViewBox.frame.size;

  //Create the bitmap context
  UIGraphicsBeginImageContext(rotatedSize);
  CGContextRef bitmap = UIGraphicsGetCurrentContext();

  //Move the origin to the middle of the image so we will rotate and scale around the center.
  CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

  //Rotate the image context
  CGContextRotateCTM(bitmap, (degrees * M_PI / 180));

  //Now, draw the rotated/scaled image into the context
  CGContextScaleCTM(bitmap, 1.0, -1.0);
  CGContextDrawImage(bitmap, CGRectMake(-oldImage.size.width / 2, -oldImage.size.height / 2, oldImage.size.width, oldImage.size.height), [oldImage CGImage]);

  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return newImage;
}

然后像这样调用它:

//Rotate it
UIImage *rotatedImage = [self imageRotatedByDegrees:signatureImage deg:90];

谢谢大家。


2
这会使角落像素化。 - durazno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接