iOS:renderInContext和Landscape orientation问题

时间:2014-07-11 09:44:39

标签: ios iphone objective-c autolayout uiinterfaceorientation

我正在尝试将iOS设备上当前显示的视图保存到某个应用中,这样做正常。但是,一旦我试图以横向方向保存UIImageView,我就遇到了问题。

请参阅以下描述我的问题的图片:

enter image description here

我正在为此应用使用自动布局,它可以在iPhone和iPad上运行。似乎ImageView总是像纵向模式一样保存,我现在有点卡住了。

这是我使用的代码:

CGSize frameSize = self.view.frame.size;

if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
    frameSize = CGSizeMake(self.view.frame.size.height, self.view.frame.size.width);
}

UIGraphicsBeginImageContextWithOptions(frameSize, NO, 0.0);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat scale = CGRectGetWidth(self.view.frame) / CGRectGetWidth(self.view.bounds);
CGContextScaleCTM(ctx, scale, scale);

[self.view.layer renderInContext:ctx];

[self.delegate photoSaved:UIGraphicsGetImageFromCurrentImageContext()];

UIGraphicsEndImageContext();

期待您的帮助!

1 个答案:

答案 0 :(得分:0)

我仍然不知道您的确切问题是什么,但使用截图代码会产生一些奇怪的图像(不是旋转或任何东西,但是太小)。你能不能试试这个代码。

+ (UIImage *)imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, .0f);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

除此之外,您必须了解UIImageCGImage之间存在巨大差异,因为UIImage包含方向,CGImage则没有。在处理图像变换时,通常使用CGImage并且获取其宽度或高度将丢弃方向。这意味着当CGImage的方向未向上(UIImageOrientationUp)时,CGImage会翻转尺寸。但通常在处理此类图像时,您需要从上下文创建[UIImage imageWithCGImage:ref scale:1.0f orientation:originalOrientation],然后使用UIImageOrientationUp。只有当您希望显式旋转图像使其没有方向(UIImagePNGRepresentation)时,您需要旋转并翻译图像并将其绘制到上下文中。

无论如何,这个方向问题现在已经解决了,CGImage尊重方向,你有一个上面已经写过的{{1}}的图像构造函数,如果我过去曾经缺少记得没错。

相关问题