iOS-旋转图像或图片



我的iOS应用程序从互联网下载一些图像并将其显示在屏幕上(iPhone人像布局)。其中一些图像更宽而不是更高,在这种情况下,当图像出现在屏幕上时,它们看起来被压扁了(想象一下宽屏幕电视缩小到iPhone宽度的画面)。我想做的是,每次图像的宽度比图像的高度宽时,我都想将图片顺时针旋转90度(进入横向布局模式),将其保存在应用程序的文档文件夹中,然后在屏幕上显示-这样,宽屏幕电视的图片(例如)看起来旋转了90度,但图像纵横比并没有完全破坏。

由于各种复杂的原因,我不能使用我的应用程序的横向布局——太多其他副作用了。这是我写的代码:

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    if(width > 1.2*height) {
        NSLog(@"rotate the image");
        CGImageRef imageRef = [image CGImage];
        image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationLeft];
    }   

然后我将图像保存到应用程序的文档文件夹中。然后打开一个新的UIViewController,它读取保存在documents文件夹中的图像文件,然后打开此图像。问题是,图像看起来根本没有旋转——只是以与原始图像相同的方式出现——没有任何旋转。我知道上面的代码试图做它应该做的事情,因为我确实在控制台中看到NSLog"旋转图像"。但不知何故,这张图像并没有被保存为旋转后的图像。

那么,我应该如何处理这个问题呢?

编辑:保存我的图像的代码:

NSString *documentsDirectory = [NSHomeDirectory()        stringByAppendingPathComponent:@"Documents"];
    // Create image name
    NSString *path = [@"" stringByAppendingFormat:@"%@%@", @"image", @".png"];
    // Create full image path
    path = [documentsDirectory stringByAppendingPathComponent:path];
    path = [NSString stringWithFormat:@"%@", path];
    // Write image to image path
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data1 writeToFile:path atomically:YES];

以下网站的解决方案最终对我有效:

http://www.catamount.com/blog/uiimage-extensions-for-cutting-scaling-and-rotating-uiimages/

最新更新