如何在UIScrollView中将UIImageView旋转90度并显示正确的图像大小并滚动?

我有一个UIImageView里面的图像是在一个UIScrollView。 我想要做的就是将这个图像旋转90度,使它默认处于横向,并设置图像的初始缩放比例,使整个图像适合滚动视图,然后放大到100%,然后放大再次缩小到最小。

这是我迄今为止:

self.imageView.transform = CGAffineTransformMakeRotation(-M_PI/2); float minimumScale = scrollView.frame.size.width / self.imageView.frame.size.width; scrollView.minimumZoomScale = minimumScale; scrollView.zoomScale = minimumScale; scrollView.contentSize = CGSizeMake(self.imageView.frame.size.height,self.imageView.frame.size.width); 

问题是,如果我设置转换,没有什么显示在滚动视图。 但是,如果我注意到变换,除了图像以外的所有东西都不是我想要的风景方向!

如果我应用转换并删除设置minimumZoomScale和zoomScale属性的代码,则图像以正确的方向显示,但是使用不正确的zoomScale,看起来像contentSize属性设置不正确 – 因为不滚动到左/右方向的图像的边缘,但顶部和底部,但在边缘。

注意:正在从URL加载图像

也许旋转图像本身适合您的需求:

  UIImage* rotateUIImage(const UIImage* src, float angleDegrees) { UIView* rotatedViewBox = [[UIView alloc] initWithFrame: CGRectMake(0, 0, src.size.width, src.size.height)]; float angleRadians = angleDegrees * ((float)M_PI / 180.0f); CGAffineTransform t = CGAffineTransformMakeRotation(angleRadians); rotatedViewBox.transform = t; CGSize rotatedSize = rotatedViewBox.frame.size; [rotatedViewBox release]; UIGraphicsBeginImageContext(rotatedSize); CGContextRef bitmap = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2); CGContextRotateCTM(bitmap, angleRadians); CGContextScaleCTM(bitmap, 1.0, -1.0); CGContextDrawImage(bitmap, CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.width, src.size.height), [src CGImage]); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } 

我相信最简单的方法(也是线程安全)是:

 //assume that the image is loaded in landscape mode from disk UIImage * LandscapeImage = [UIImage imageNamed: imgname]; UIImage * PortraitImage = [[UIImage alloc] initWithCGImage: LandscapeImage.CGImage scale: 1.0 orientation: UIImageOrientationLeft]; 

基于imageView框架的任何计算都应该在对其应用任何转换之前完成。 但我实际上build议根据UIImage的大小做这些计算,而不是UIImageView。 然后根据这个设置UIImageView的框架和UIScrollView的contentSize。

马克斯的build议是一个很好的build议,尽pipe更大的形象可能是一个性能杀手。 你是从应用程序的资源中显示这个图像? 如果是这样,为什么不在创build应用程序之前旋转图像呢?

有一个更简单的解决scheme也更快,只是这样做:

 - (void) imageRotateTapped:(id)sender { [UIView animateWithDuration:0.33f animations:^() { self.imageView.transform = CGAffineTransformMakeRotation(RADIANS(self.rotateDegrees += 90.0f)); self.imageView.frame = self.imageView.superview.bounds; // change this to whatever rect you want }]; } 

当用户完成后,您将需要实际创build一个新的旋转的图像,但是这非常容易。

我一直在使用接受的答案,直到我们注意到基于直接从相机拍摄的图像的非方形旋转似乎被拉长(它们被旋转为所需的,只是帧宽度/高度未被调整)。

伟大的解释/从Trevor这里发表: http : //vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/

最后,这是一个非常简单的Trevor代码导入,它使用类别向UIImage添加resizedImage:interpoationQuality方法。 所以,是的,用户要小心,如果它仍然适用于你,很好。 但是,如果没有,我会看看图书馆。