简体   繁体   English

如何从iOS中旋转,缩放和倒置的UIImageView中提取UIImage

[英]How to extract the UIImage from rotated, scaled and inverted UIImageView in iOS

I am taking a image from the Gallery and applying scale, rotate and invert transformations using CGAffineTransform. 我正在从图库中拍摄图像,并使用CGAffineTransform应用缩放,旋转和反转转换。 Finally I am saving the Image to the Gallery. 最后,我将图像保存到图库。 But the saved Image is having white rectangle boundary![Rotated UIImageView with White background][1]. 但是,已保存的图像具有白色矩形边界![具有白色背景的旋转UIImageView] [1]。

- (UIImage *)getTheTransformedOriginalImage:(UIImage *)aTransImage
  {
    CGAffineTransform transform = selImageView.transform;
   CGPathRef rotatedImageRectPath = CGPathCreateWithRect(selImageView.frame, &transform);
    CGRect boundingBox = CGPathGetBoundingBox(rotatedImageRectPath);

   CGSize rotatedSize = boundingBox.size;

   UIGraphicsBeginImageContext(rotatedSize);
   UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 0.0f);

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

//Rotate the image context using tranform
   CGContextConcatCTM(UIGraphicsGetCurrentContext(), selImageView.transform);
// Now, draw the rotated/scaled image into the context
   CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
   CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(-aTransImage.size.width / 2, -aTransImage.size.height / 2, aTransImage.size.width, aTransImage.size.height), [aTransImage CGImage]);

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

- (IBAction)saveToGalleryClicked:(id)sender
  {
      UIImage *aTransImage = selImageView.image;
      UIImage *shareImage = [self getTheTransformedOriginalImage:aTransImage]
      UIImageWriteToSavedPhotosAlbum(shareImage, nil, nil, nil);
   }

I have added the rotated UIImage in the attachment. 我在附件中添加了旋转的UIImage。

In order to not have a white background (ie an opaque image), you need to use a different function to begin the image context: 为了没有白色背景(即不透明图像),您需要使用其他函数来开始图像上下文:

 UIGraphicsBeginImageContextWithOptions(CGSize size, **BOOL opaque**, CGFloat scale) 

So, replace: 因此,请替换:

 UIGraphicsBeginImageContext(rotatedSize);

With: 带有:

 UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, [[UIScreen mainScreen]scale])

This will make sure that the context is drawn with transparency. 这样可以确保上下文透明地绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM