iOS,尝试使用UIGraphicsGetImageFromCurrentImageContext渲染“变换缩放”视图时出现意外结果

时间:2013-02-27 07:05:49

标签: ios uiview uiimageview render

我试图在使用UIGraphicsGetImageFromCurrentImageContext进行转换后渲染视图及其内容。即使视图按比例缩小,当我渲染视图时,图像大小也是正确的,但内容会以原始大小呈现(在这种情况下,它们会被裁剪,而不是像预期的那样适合视图。

enter image description here

这是一个简单的示例项目:http://owolf.net/uploads/StackOverflow/ParentChildTransformTester.zip

进一步解释:我创建父视图和子视图,将子视图添加为子视图。然后我转换缩放父视图,也调整子视图的大小(就像我想要的那样)。然后我在父视图的当前帧大小上创建一个图像上下文,并进行渲染。代码如下。

//create views
UIView *parentView = [[UIView alloc]initWithFrame:self.view.bounds];
[parentView setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:parentView];

UIView *childView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
[childView setBackgroundColor:[UIColor redColor]];
[parentView addSubview:childView];

//log parent view size : result is device screen size
NSLog(@"parentView.frame.size, BEFORE tran: %f x %f", parentView.frame.size.width, parentView.frame.size.height);

float scaleFactor = 0.2;
CGAffineTransform trans = CGAffineTransformScale(CGAffineTransformIdentity, scaleFactor, scaleFactor);
parentView.transform = trans;

//log parent view size after transform :  result is device screen size * 0.2
NSLog(@"parentView.frame.size, AFTER tran: %f x %f", parentView.frame.size.width, parentView.frame.size.height);


//attemt to render and save scaled parent view.
CGSize renderSize = CGSizeMake(parentView.frame.size.width, parentView.frame.size.height);
UIGraphicsBeginImageContext(CGSizeMake(renderSize.width, renderSize.height));

[[parentView layer] renderInContext:UIGraphicsGetCurrentContext()];

UIImage *renderedImage;
renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(renderedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

2 个答案:

答案 0 :(得分:0)

在渲染图层之前,需要将变换应​​用于当前变换矩阵:

...
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextConcatCTM(ctx, [[parentView layer] affineTransform]);

[[parentView layer] renderInContext:ctx];
...

答案 1 :(得分:0)

这很有效:根据Graver上面的回答进行了修改。

UIGraphicsBeginImageContext(parentView.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextConcatCTM(ctx, [[parentView layer] affineTransform]);
[[parentView layer] renderInContext:UIGraphicsGetCurrentContext()];
renderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(renderedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);