1

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

在此处输入图像描述

这是一个简单的示例项目: 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);
4

2 回答 2

0

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

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

[[parentView layer] renderInContext:ctx];
...
于 2013-02-27T07:20:26.087 回答
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);
于 2013-02-27T07:29:31.543 回答