我有一个包含UIImageView的UIView,我将旋转变换应用到UIImageView,然后想要在CGContext中使用相同的旋转变换绘制该图像(以及将来更多的变换,如转换和规模将被使用),我有以下代码进行CGContext中的转换和绘制:用CGContext绘制CGAffineTransform的UIImage奇怪的输出
UIImage *image=[UIImage imageNamed:@"cena-1.png"];
CGRect imageFrame=CGRectMake(50, 50, image.size.width, image.size.height);
UIImageView *imageView=[[UIImageView alloc] initWithFrame:imageFrame];
imageView.image=image;
[self.view addSubview:imageView];
CGAffineTransform imageTransform=CGAffineTransformMakeRotation(degreesToRadians(10));
imageView.transform=imageTransform;
NSLog(@"self.imgOverlay.image.scale: %f", imageView.image.scale);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
CGContextConcatCTM(context, imageView.transform);
CGRect modifiedRect=CGRectApplyAffineTransform(imageFrame, imageTransform);
[imageView.image drawInRect:modifiedRect];
UIGraphicsPopContext();
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *jpgPath=[NSTemporaryDirectory() stringByAppendingPathComponent:@"test.jpg"];
NSData *imageData=UIImageJPEGRepresentation(outputImage, 1.0);
[imageData writeToFile:jpgPath atomically:YES];
NSLog(@"putputImage path: %@", jpgPath);
。
问题是outputimage看起来不一样,因为它是UIKit中的UIView的显示,它被扭曲和位置是不准确的为好,这里是截图:
请指引我关于我在做什么错,谢谢你的帮助:)
ps我还发布了另一个问题(https://stackoverflow.com/questions/17873202/uiimage-drawn-in-cgcontext-with-cgaffinetransform-unexpected-results),解释了完整的场景,但对这个问题的回答有望足够。
UPDATE 我试图[imageView.image drawAtPoint:modifiedRect.origin];
它纠正歪斜问题(http://screencast.com/t/v2oKkmkd),但位置问题仍然:(
更新2 下面是一个测试项目,一点点修改后的代码:https://github.com/abduliam/TestTransform
尝试使用PNG表示...有时JPEG功能莫名其妙地不工作,但PNG功能一样。 –
@DylanKirkby感谢您的评论,尝试过(http://screencast.com/t/0mgge4LEHRF)没有运气,情况更加复杂,我认为它与CG和UIKit的坐标系的差异有关: ) –